Search code examples
powershellpowershell-5.0

powershell wait for command to finish before proceeding


In powershell I am trying to do the following:

$name = "computername"
#get installed programs
Write-Host "****APPLICATIONS"
gwmi win32_Product -ComputerName $name | select name

#gets services
write-host "****SERVICES"
Get-Service -ComputerName $name | ft

the expected output would be

****APPLICATIONS
name
of
app

****SERVICES
running services here
more services here

the actual result is

****APPLICATIONS
****SERVICES
name
of
app
running services here
more services here

I have attempted to do start-job then wait-job , but running gwmi as a job seems to output nothing to the console and sending the output to a separate file defeats the purpose of other parts of the script

I also attempted to use start-sleep and it still finishes both write-host commands before proceeding


Solution

  • Try this:

    $name = "computername"
    Write-Host "`n****APPLICATIONS`n"
    gwmi win32_Product -ComputerName $name | % {$_.name}
    write-host "`n****SERVICES"
    Get-Service -ComputerName $name | ft
    

    If you want the results alphabetical:

    $name = "computername"
    Write-Host "`n****APPLICATIONS`n"
    $apps = gwmi win32_Product -ComputerName $name | % {$_.name}
    $apps | sort
    write-host "`n****SERVICES"
    Get-Service -ComputerName $name | ft