PowerShell脚本多次使用Write-Host后输出顺序异常求助
解决PowerShell中Write-Host与命令输出顺序错乱的问题
问题根源
PowerShell的输出分为不同流:
Write-Host直接写入主机流,内容会立即显示在控制台Search-ADAccount这类命令的输出默认进入成功输出流,PowerShell会缓冲该流内容,直到当前脚本执行上下文结束后才统一输出
这就导致所有Write-Host的提示文本先全部显示,再批量展示所有AD查询结果的问题。
解决方案
在每个AD查询的管道末尾添加| Out-Host,强制将输出流内容立即发送到控制台,和Write-Host的输出保持顺序一致。
修改后的脚本
#Use this script to find all acounts in the External Contractors OU with accounts that have expired and will expire with in the next 365 days $cred = Get-Credential Write-Host "Accounts due to expire in the next 365 days" -ForegroundColor red -BackgroundColor white Search-ADAccount -Server teeis0002.europe.tel.com -Credential $cred ` -searchbase "OU=External Contractors,OU=Users,OU=xxxxxx,DC=xxxxxx,DC=xxxxxx,DC=xxxxx" ` -AccountExpiring -TimeSpan 365.00:00:00 -UsersOnly -ResultPageSize 2000 -resultSetSize $null | Select-Object Name, UserPrincipalName, DistinguishedName, AccountExpirationDate | Sort-Object -Property AccountExpirationDate | Out-Host Write-Host "Currently Expired Accounts" -ForegroundColor red -BackgroundColor white Search-ADAccount -Server teeis0002.europe.tel.com -Credential $cred ` -searchbase "OU=External Contractors,OU=Users,OU=xxxxxx,DC=xxxxxx,DC=xxxxxx,DC=xxxxx" ` -AccountExpired -UsersOnly -ResultPageSize 2000 -resultSetSize $null | Select-Object Name, UserPrincipalName, DistinguishedName, AccountExpirationDate | Sort-Object -Property AccountExpirationDate | Out-Host
补充说明
Out-Host会把输入对象按PowerShell默认格式格式化后直接输出到控制台,绕过输出流缓冲,实现即时显示- 若不想使用
Out-Host,也可以用[Console]类直接控制颜色并输出文本(替代Write-Host),示例:
这种方式下[Console]::ForegroundColor = 'Red' [Console]::BackgroundColor = 'White' Write-Output "Accounts due to expire in the next 365 days" [Console]::ResetColor()Write-Output的内容和AD命令输出同属输出流,也会按顺序显示,但需要手动恢复控制台颜色,相对繁琐
内容的提问来源于stack exchange,提问作者Murray Mint
相关产品推荐
相关产品推荐

