首页 > 解决方案 > 获取 AD 组时,PowerShell 脚本未按预期工作

问题描述

我正在使用带有菜单的 PowerShell 脚本来选择在 Active Directory 中搜索信息的不同方式。带有 Get-ADUser 的命令可以正常工作,但带有 Get-ADPrincipalGroupMembership 的命令有一个奇怪的行为。当我选择该选项 (3) 并输入用户名并运行命令时,没有任何内容会输出到显示器,如果我随后使用菜单上的 (Q) 退出,则会显示组。

function Show-Menu 
{ 
     param ( 
           [string]$Title = 'AD Search Tool' 
     ) 
     cls 
     Write-Host "================ $Title ================" 

     Write-Host "1: Search Users by Title" 
     Write-Host "2: Press '2' for this option." 
     Write-Host "3: List User's Groups" 
     Write-Host "Q: Press 'Q' to quit." 
} 

do 
{ 
     Show-Menu 
     $input = Read-Host "Please make a selection" 
     switch ($input) 
     { 
           '1' { 
                cls 
                $title = Read-Host -Prompt 'Enter Title'
                if ($title){
                    Get-ADUser -Properties SamAccountName, Enabled, Title, EmployeeID -Filter "(Title -eq '$title') -and (Enabled -eq 'True')" | select Enabled, EmployeeID, Name, SamAccountName, Title 
                }

           } '2' { 
                cls 
                'You chose option #2' 

           } '3' { 
                cls 
                $user = Read-Host -Prompt 'Enter User Name'
                if ($user){
                    Get-ADPrincipalGroupMembership $user | select name | sort name 
                }

           } 'q' { 
                cls
                return 
           } 
     } 
     pause 
} 
until ($input -eq 'q')

标签: powershellactive-directory

解决方案


只需使用Write-Host立即写入结果。要通过管道做到这一点,你可以Out-String先使用。

所以

 Get-ADPrincipalGroupMembership $user | select name | sort name  | Out-String | Write-Host -ForegroundColor Cyan

代替

 Get-ADPrincipalGroupMembership $user | select name | sort name

会成功的。* 颜色是可选的。我只是喜欢青色。


推荐阅读