powershell在继续之前等待命令完成

时间:2017-01-12 21:22:10

标签: powershell powershell-v5.0

在powershell中,我尝试执行以下操作:

$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

预期输出为

****APPLICATIONS
name
of
app

****SERVICES
running services here
more services here

实际结果是

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

我曾尝试start-job然后wait-job,但运行gwmi作为工作似乎没有输出到控制台并将输出发送到单独的文件会破坏脚本其他部分的目的

我还尝试使用start-sleep,在继续之前仍然完成两个write-host命令

2 个答案:

答案 0 :(得分:0)

Param(
    $ComputerName = 'AT805061'
)

# Get installed programs
Write-Host "`n****APPLICATIONS`n"
Get-WmiObject win32_Product -ComputerName $ComputerName | Select-Object -ExpandProperty Name | Sort-Object

# Get services
Write-Host "`n****SERVICES`n"
Get-Service -ComputerName $ComputerName | Where-Object -Property Status -eq -Value Running | Select-Object -ExpandProperty Name | Sort-Object

答案 1 :(得分:0)

试试这个:

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

如果您希望结果按字母顺序排列:

$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