Powershell似乎异步运行语句



我编写了一个powershell cmdlet,它在Server 2012 R2(powershell 4.0(上运行良好,但在Windows 10或Server 2016(powershell 5.1(上,命令似乎不会等待对方完成,而是异步执行(?(。这当然不是所需的行为,并导致cmdlet无法按预期运行。

脚本的核心启动一个转录本,运行Get-ADFPrincipalGroupMembership,然后运行Get-ADUser,最后运行Get-Date,最后关闭转录本。

try {
Start-Transcript -Path $transactionFilename
Write-Host "GROUP MEMBERSHIP FOR $($targetUsername)"
Get-ADPrincipalGroupMembership -Credential $credential -Identity $Username -Server $domainServer | select name,distinguishedName | format-table
Write-Host "ACCOUNT PROPERTIES FOR $($targetUsername)"
Get-ADUser -Credential $credential -Identity $Username -Server $domainServer -Properties *
Write-Host "CURRENT TIME"
(Get-Date).DateTime
} catch {
} finally {
Stop-Transcript 
write-host "Transcript is available at"
write-host $transactionFilename
$Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size ($originalHostWidth, $hostHeight)
}

在PS 4.0上运行时,每个语句都按顺序执行-每个语句都在等待前一个语句完成。

👍

在PS 5.1上运行时,Get-ADPrincipalGroupMembership结束,然后Write-Host "ACCOUNT PROPERTIES"运行,然后Write-Host "CURRENT TIME"运行,然后在finally块中的所有内容都运行,然后运行Get-ADUserGet-Date命令。

👎

正如您可以想象的那样,在脚本中间运行Stop-Transcript是一个很好的例子!

我在谷歌上搜索了阻止cmdlet异步执行的方法,但所有的文章都是关于如何使其异步执行的,而不是如何停止它。我现在不知道该在哪里寻求帮助。

如何调整powershell 5.1以同步运行语句?与4.0的向后兼容性并不是绝对必要的,但这将是一个额外的好处。

根据@Lee_Dayey和@js2010的评论,我可以通过将输出从format-tableGet-ADUser管道传输到Out-Host:来修改脚本,使其按需运行

try {
Start-Transcript -Path $transactionFilename
Write-Host "GROUP MEMBERSHIP FOR $($targetUsername)"
Get-ADPrincipalGroupMembership -Credential $credential -Identity $Username -Server $domainServer | select name,distinguishedName | format-table | out-host
Write-Host "ACCOUNT PROPERTIES FOR $($targetUsername)"
Get-ADUser -Credential $credential -Identity $Username -Server $domainServer -Properties * | out-host
Write-Host "CURRENT TIME"
(Get-Date).DateTime
} catch {
} finally {
Stop-Transcript 
write-host "Transcript is available at"
write-host $transactionFilename
$Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size ($originalHostWidth, $hostHeight)
}

最新更新