我有一个powershell脚本,它将许多主机名作为输入,然后在其中安装IE11和Office 2010。目前它将这些安装在一个主机中,然后继续下一个主机等。这只是浪费时间,因为一个安装不会影响另一个。那我怎么能让它并行运行呢? TIY 这是我的代码:
Write-Host "*************************************************"
Write-Host "Welcome to the IE11/Office 2010 Remote Installer"
Write-Host "*************************************************"
$pclist = (Read-Host "Enter the pc names seperated by comma").Split(",")
foreach ($pc in $pclist) {
Write-Host "-------------------------------------------------------------------------------------------------------"
Write-Host "Installing IE in $($pc). Please look for the exit code in the end. Exit code 0 means successful"
psexec -s \\$pc \\myserver\directory\PREREQ.BAT
psexec -s \\$pc \\myserver\directory\INSTALL.BAT
Write-Host "-------------------------------------------------------------------------------------------------------"
Write-Host "Installing office in $($pc). Please look for the exit code in the end. Exit code 0 means successful"
psexec -s \\$pc \\myserver\directory\INSTALL.BAT
Write-Host "-------------------------------------------------------------------------------------------------------"
Write-Host "RESTART THE PC TO APPLY CHANGES"
}
答案 0 :(得分:1)
查看Start-Job,Wait-Job和Receive-Job
我删除了Write-Host
语句,使其更易于阅读。
$jobs = $pclist | % {
Start-Job -ScriptBlock {
$target = $args[0]
psexec -s \\$target \\myserver\directory\PREREQ.BAT
psexec -s \\$target \\myserver\directory\INSTALL.BAT
psexec -s \\$target \\myserver\directory\INSTALL.BAT
} -ArgumentList $_
}
$jobs | Wait-Job | Receive-Job
当作业仍然通过Register-EngineEvent运行时接收输出的更新:
$null = Register-EngineEvent -SourceIdentifier PcInstallMsg -Action {
Write-Host $Event.MessageData
}
$jobs = $pclist | % {
Start-Job -ScriptBlock {
$null = Register-EngineEvent -Forward -SourceIdentifier PcInstallMsg
$target = $args[0]
$null = New-Event -SourceIdentifier PcInstallMsg -MessageData "Install pre-req stuff to $target"
Start-Sleep -Seconds 2
$null = New-Event -SourceIdentifier PcInstallMsg -MessageData "Install main stuff to $target"
Start-Sleep -Seconds 2
$null = New-Event -SourceIdentifier PcInstallMsg -MessageData "Do cleanup bc I was messy on $target"
Start-Sleep -Seconds 2
} -ArgumentList $_
}
while (-not (Wait-Job $jobs -Timeout 1)) {
}
$jobs | Receive-Job
Unregister-Event -SourceIdentifier PcInstallMsg