使用流水线命令同步写入 foreach 内的命令行
Write synchronously to the command line inside a foreach with a pipelined command
我有以下代码:
Get-ResourcePool -Server 1.1.1.1 | Where-Object {$_.Name -like 'XX*'} | foreach {
Write-Host $_.Name -ForegroundColor Red
Get-ResourcePool -Name $_.Name | Get-VM
}
由于管道的原因,它是异步执行的 - 所以所有的 Write-Host 输出都出现在控制台上,只有在那之后我才从 Get-ResourcePool 获得结果。
问题:如何使其同步 - 如何在执行下一个 foreach 循环之前等待管道完成。
P.S。我能够确定问题出在管道上,因为当我移除 for each 中的管道时,我得到了我期望的结果。
P.P.S 我尝试了 Start-Job -ScriptBlock { Get-ResourcePool -Name $Input | Get-VM } -InputObject "$_.Name"
然后等待作业完成 - 但是这不起作用,因为我需要在运行此命令时连接到 vCenter,所以我得到:
7/1/2019 6:37:49 PM Get-ResourcePool You are not currently connected to any servers. Please connect first using a Connect cmdlet.
+ CategoryInfo : ResourceUnavailable: (:) [Get-ResourcePool], ViServerConnectionException
+ FullyQualifiedErrorId : Core_BaseCmdlet_NotConnectedError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetResourcePool
+ PSComputerName : localhost
附录:
添加带有一些建议的屏幕截图 - 不幸的是 none 其中有效:
reddit 的建议也不起作用:https://www.reddit.com/r/PowerShell/comments/8hvjyn/output_delay/
在最后添加一个停顿:
在最后添加暂停和 Out-Host:
how do I wait for the pipeline to finish before executing the next foreach cycle.
您可以使用 Out-Default
:
强制同步输出到主机应用程序
Get-ResourcePool -Server 1.1.1.1 | Where-Object {$_.Name -like 'XX*'} | ForEach-Object {
Write-Host $_.Name -ForegroundColor Red
Get-ResourcePool -Name $_.Name | Get-VM | Out-Default
}
问题解决了:是我个人的错误。我正在使用资源池进行测试,其中唯一具有任何 VM 的资源池是最后一个。我把它改成包含多个虚拟机的资源池并测试后,我可以看到它工作正常。
我有以下代码:
Get-ResourcePool -Server 1.1.1.1 | Where-Object {$_.Name -like 'XX*'} | foreach {
Write-Host $_.Name -ForegroundColor Red
Get-ResourcePool -Name $_.Name | Get-VM
}
由于管道的原因,它是异步执行的 - 所以所有的 Write-Host 输出都出现在控制台上,只有在那之后我才从 Get-ResourcePool 获得结果。
问题:如何使其同步 - 如何在执行下一个 foreach 循环之前等待管道完成。
P.S。我能够确定问题出在管道上,因为当我移除 for each 中的管道时,我得到了我期望的结果。
P.P.S 我尝试了 Start-Job -ScriptBlock { Get-ResourcePool -Name $Input | Get-VM } -InputObject "$_.Name"
然后等待作业完成 - 但是这不起作用,因为我需要在运行此命令时连接到 vCenter,所以我得到:
7/1/2019 6:37:49 PM Get-ResourcePool You are not currently connected to any servers. Please connect first using a Connect cmdlet.
+ CategoryInfo : ResourceUnavailable: (:) [Get-ResourcePool], ViServerConnectionException
+ FullyQualifiedErrorId : Core_BaseCmdlet_NotConnectedError,VMware.VimAutomation.ViCore.Cmdlets.Commands.GetResourcePool
+ PSComputerName : localhost
附录:
添加带有一些建议的屏幕截图 - 不幸的是 none 其中有效:
reddit 的建议也不起作用:https://www.reddit.com/r/PowerShell/comments/8hvjyn/output_delay/
在最后添加一个停顿:
在最后添加暂停和 Out-Host:
how do I wait for the pipeline to finish before executing the next foreach cycle.
您可以使用 Out-Default
:
Get-ResourcePool -Server 1.1.1.1 | Where-Object {$_.Name -like 'XX*'} | ForEach-Object {
Write-Host $_.Name -ForegroundColor Red
Get-ResourcePool -Name $_.Name | Get-VM | Out-Default
}
问题解决了:是我个人的错误。我正在使用资源池进行测试,其中唯一具有任何 VM 的资源池是最后一个。我把它改成包含多个虚拟机的资源池并测试后,我可以看到它工作正常。