我正在嘗試在多台電腦上同時執行我擁有的 PowerShell 腳本。目前,我使用的是 PowerShell 版本 5。
我想知道是否可以在沒有後台進程的情況下運行它,以檢查對日誌的更好理解。
$computers = @("Hostname1", "Hostname2", "Hostname3")
$scriptPath = "C:\Projects\Scripts\Environment\InstallEnvironment.ps1"
$scriptBlock = {
param (
[string]$scriptPath
)
try {
# Execute the script
& $scriptPath
}
catch {
Write-Host "Error occurred on $($env:COMPUTERNAME): $_"
}
}
foreach ($computer in $computers) {
Start-Job -ScriptBlock $scriptBlock -ArgumentList $scriptPath -Name $computer
}
while (Get-Job -State Running) {
Start-Sleep -Milliseconds 100
}
Get-Job | Receive-Job
Get-Job | Remove-Job
非常感謝任何幫助。
答案1
我認為你有三個選擇:
- 繼續賈伯斯,但稍微重構你的程式碼
ForEach-Object -Parallel
在 PowerShell 7 中使用- 嘗試使用工作流程在 PowerShell 5 中,這
foreach -Parallel ($a in $x) {}
是另一個令人頭痛的問題
Invoke-Command
以下是用於建立作業並Wait-Job
等待它們的程式碼片段:
$computers = @("Hostname1", "Hostname2", "Hostname3")
$scriptPath = "C:\Projects\Scripts\Environment\InstallEnvironment.ps1"
$scriptBlock = {
try {
& $Using:scriptPath
}
catch {
Write-Host "Error occurred on $($env:COMPUTERNAME): $_"
}
}
$Jobs = Invoke-Command -ScriptBlock $scriptBlock -ComputerName $computers -AsJob
# Results (Logs) are stored in the $Result variable
$Result = $Jobs | Wait-Job | Receive-Job
$Jobs | Remove-Job
這是您可以使用的方法ForEach-Object -Parallel
,但請注意,有時這不會讓您像平常那樣將內容輸出到控制台,並且可能會給您帶來其他類型的麻煩:
#Requires -Version 7
$computers = @("Hostname1", "Hostname2", "Hostname3")
$scriptPath = "C:\Projects\Scripts\Environment\InstallEnvironment.ps1"
$scriptBlock = {
try {
& $Using:scriptPath
}
catch {
Write-Host "Error occurred on $($env:COMPUTERNAME): $_"
}
}
$computers | ForEach-Object -Parallel {
Invoke-Command -ScriptBlock $scriptBlock -ComputerName $_
}
我絕對建議留在喬布斯並通過以下方式獲取您的日誌Receive-Job