【问题标题】:Output of a PowerShell command doesn't show result until after Write-Host and Read-HostPowerShell 命令的输出在 Write-Host 和 Read-Host 之后才显示结果
【发布时间】:2019-08-29 21:38:30
【问题描述】:

在我在代码末尾按回车之前,代码不会返回 Get-ADUser 命令的结果

    Write-Host "Please enter the user account name. Ex. jsmith1" -ForegroundColor Yellow -BackgroundColor Black
$Username = Read-Host
"`n"

Write-Host "Is this the correct username?  $Username" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue1 = Read-Host

IF ($Continue1 -eq 1)
{
  Get-ADUser -Server "contoso.com" -filter * -Properties * | Where {$_.SamAccountName -match $Username} | Select DisplayName, SamAccountName, EmployeeID, EmployeeNumber
}
ELSE
{}

Write-Host "Would you like to update the Employee ID and the Employee Number?" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue2 = Read-Host

我在这里错过了什么?

【问题讨论】:

标签: powershell active-directory


【解决方案1】:

Write-Host 项目会在您的命令执行期间立即显示。

Get-ADUser 结果在输出管道上。

通常,这允许您将值返回到另一个脚本中,例如,用于进一步处理。由于您没有分配它或捕获输出,它只是转到默认格式化程序并在执行结束之前显示在其他所有内容之后。

如果您真的只想显示输出,可以将| Write-Host 添加到Get-ADUser 调用的末尾。如果您想将此连接到另一个脚本,您可以将值捕获到一个变量中,然后将 Write-HostWrite-Output 都添加回管道中。

另请参阅:Understanding the Windows PowerShell Pipeline

【讨论】:

  • 抱歉,我花了这么长时间才接受这个答案。完全合乎逻辑且易于理解的解释。
【解决方案2】:

我发现您也可以在末尾添加一些格式,它会在您期望的时候按您的期望输出。我在末尾添加了这种格式:

| FT -AutoSize

【讨论】:

  • 谢谢你,这对我有用。我的脚本使用“| Select-Object ..”在列中显示数据。 " | Write-Host" 弄乱了格式,但 " | ft -AutoSize" 没有。
猜你喜欢
  • 2023-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-13
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多