Search code examples
powershellpowercli

Write synchronously to the command line inside a foreach with a pipelined command


I have the following code:

Get-ResourcePool -Server 1.1.1.1 | Where-Object {$_.Name -like 'XX*'} | foreach {
    Write-Host $_.Name -ForegroundColor Red
    Get-ResourcePool -Name $_.Name | Get-VM
}

Which is executed asynchronously, due to pipeline - so all of the Write-Host outputs appear on the console and only after that I get the result from Get-ResourcePool.

Question: how do I make it synchronous - how do I wait for the pipeline to finish before executing the next foreach cycle.

P.S. I was able to determine that the problem is with the pipeline because when I remove the pipe inside the for each I get what I expect.

P.P.S i tried Start-Job -ScriptBlock { Get-ResourcePool -Name $Input | Get-VM } -InputObject "$_.Name" and then wait for the job to finish - but that does not work due to fact that I need to be connected to the vCenter while this command runs, so I get:

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

ADDENDUM: Adding screenshots with some of the suggestions - unfortunately none of them work: enter image description here

Suggestion from reddit also does not work: https://www.reddit.com/r/PowerShell/comments/8hvjyn/output_delay/

enter image description here

Adding a pause at the end: enter image description here

Adding pause and Out-Host at the end: enter image description here


Solution

  • Solved the issue: it was my personal mistake. I was testing with resource pools where the only resource pool having any VMs was the last one. After I changed it to resource pool containing multiple VMs and tested it, I was able to see it working fine.