通过PowerShell查询AD用户组成员:菜单选项3输出空白问题
解决AD用户菜单脚本中"Show Groups"选项输出为空的问题
让我来帮你排查这个问题,我看了你的脚本,发现几个关键点导致选项3输出为空,还有其他小问题需要修复:
主要问题:Filter参数的变量解析错误
你的Get-ADUser命令里用了单引号包裹Filter条件:
Get-ADUser -F 'name -like $search' | FT SamAccountName -A
在PowerShell中,单引号里的变量不会被解析,所以实际执行的过滤条件是name -like $search(而不是你期望的带通配符的字符串,比如*John*)。这意味着这一步根本搜不到你要找的用户,后续输入的$target_user可能是一个不存在的账号,自然调用Get-ADPrincipalGroupMembership时输出为空。
次要问题:命令拼写错误
选项2里的Disabled-ADAccount是拼写错误,正确的命令是Disable-ADAccount(多了一个末尾的d),这个错误会导致选项2执行失败。
修复后的完整脚本
下面是修复后的脚本,我还调整了一些细节让体验更流畅:
function Show-Menu { param ( [string]$Title = 'AD User Management Menu' ) Clear-Host Write-Host "================ $Title ================" Write-Host "1: Unlock User" Write-Host "2: Disable User" Write-Host "3: Show User's Groups" Write-Host "Q: Press 'Q' to quit." } # User Lookup Clear-Host Write-Host 'First, let''s look up the user you want to work with' $user = Read-Host 'Enter the name of the user you want to search for' $search = "*$user*" # 用双引号包裹Filter,让变量正常解析 Get-ADUser -Filter "name -like '$search'" | Format-Table SamAccountName -AutoSize # User Selection $target_user = Read-Host 'Enter the SamAccountName of the user you want to work with' # 验证用户是否存在(新增步骤,避免无效输入) try { Get-ADUser -Identity $target_user | Out-Null } catch { Write-Host "Error: User '$target_user' does not exist in AD!" -ForegroundColor Red pause exit } Clear-Host do { Show-Menu $selection = Read-Host "Please make a selection" switch ($selection) { '1' { Unlock-ADAccount -Identity $target_user Write-Host "User '$target_user' has been unlocked successfully!" -ForegroundColor Green } '2' { # 修复拼写错误 Disable-ADAccount -Identity $target_user Write-Host "User '$target_user' has been disabled successfully!" -ForegroundColor Green } '3' { Clear-Host Write-Host "Groups for user '$target_user':`n" # 输出更清晰的组列表 Get-ADPrincipalGroupMembership $target_user | Select-Object Name | Format-Table -AutoSize } 'q' { Write-Host "Exiting script..." -ForegroundColor Cyan } default { Write-Host "Invalid selection! Please choose a valid option or 'Q' to quit." -ForegroundColor Red } } if ($selection -ne 'q') { pause } } until ($selection -eq 'q') Clear-Host
额外优化说明
- 新增了用户存在性验证,避免后续操作因为无效账号报错
- 为每个操作添加了成功/错误提示,提升用户体验
- 优化了选项3的输出格式,让组列表更易读
- 处理了无效输入的情况,避免脚本无响应
现在你运行修复后的脚本,选项3应该能正常输出用户的组成员了!
内容的提问来源于stack exchange,提问作者Daniel
相关产品推荐
相关产品推荐

