David David - 3 months ago 17
PowerShell Question

Wait until previous command is completed in powershell

Here is the issue I am facing. I am looking through a group variable. It pulls the information but it doesn't display it line by line. Instead, it will present the last groups info sometimes before the group members and then sometimes after. It seems to be dropping the process into a subprocess then continuing to the next line which might process faster. I know I am missing something simple. Here is the code:

foreach ($Groups in $Groups) {
Write-Host "---------- Group Info ----------" -ForegroundColor Yellow
$TempGroup = $Groups
$GroupInfo = Get-ADGroup -Filter "name -like '$TempGroup'" -Properties *
$GroupInfo | select Name,GroupScope,GroupCategory,mail,Created,Modified,DistinguishedName,Description | sort name

write-host "---------- Members ----------" -ForegroundColor Green
Get-ADGroupMember -Identity $GroupInfo.samaccountname -Recursive | select name,samaccountname,description | sort name | ft -AutoSize

write-host "---------- Nested Groups ----------" -ForegroundColor Green
Get-ADPrincipalGroupMembership -Identity $GroupInfo.samaccountname | select name,GroupScope,GroupCategory | sort name | ft -AutoSize | Wait-Job

}


Groups is an array.

Answer

Mixing Write-Host with default output from uncaught objects can give you strange results. Write-Host writes directly to the host (console), while the returned objects are sent down the pipeline until it reaches Out-Default (hidden cmdlet) which formats the objects and outputs them to the console (default output).

Pipe the objects directly to Out-Host to avoid this delay. Try:

foreach ($Group in $Groups) {
    Write-Host "---------- Group Info ----------" -ForegroundColor Yellow
    $TempGroup = $Group
    $GroupInfo = Get-ADGroup -Filter "name -like '$TempGroup'" -Properties *    
    $GroupInfo | select Name,GroupScope,GroupCategory,mail,Created,Modified,DistinguishedName,Description | sort name | Out-Host

    write-host "---------- Members ----------" -ForegroundColor Green
    Get-ADGroupMember -Identity $GroupInfo.samaccountname -Recursive | select name,samaccountname,description | sort name | ft -AutoSize | Out-Host

    write-host "---------- Nested Groups ----------" -ForegroundColor Green
    Get-ADPrincipalGroupMembership -Identity $GroupInfo.samaccountname | select name,GroupScope,GroupCategory | sort name | ft -AutoSize | Out-Host

}

Also...

  1. Wait-Job does nothing here because it never recieved a job-object from the cmdlets earlier in the pipeline.
  2. You're using the same variable for the current object and the array in your foreach-loop. I can't remember if PowerShell understands your referring to the current item inside the loop, but at least it makes your code hard to read.