我有一个脚本,但执行起来要花几个小时。我需要做什么才能让它并行运行?
$servers = Get-Content -Path c:\Scripts\MyServerList.txt
foreach ($Server in $servers)
{
Write-Output $Server;
Get-EventLog -LogName System -EntryType Error -ComputerName $Server | Measure-Object
}
答案1
引用这Stack Overflow 帖子。
在我的 3 台服务器上运行您的构建耗时 2:23。
运行以下脚本花费了 2:07。节省的时间不多,但运行较大的数字可能会节省更多时间。我认为您也可以在最后调整输出方式。
# Loop through the server list
Get-Content "C:\scripts\Servers.txt"| %{
# Define what each job does
$ScriptBlock = {
param($Server)
Write-Output $Server;
Get-EventLog -LogName System -EntryType Error -ComputerName $Server | Measure-Object|Out-String -Stream
}
# Execute the jobs in parallel
Start-Job $ScriptBlock -ArgumentList $_
}
# Wait for it all to complete
While (Get-Job -State "Running")
{
Start-Sleep 1
}
# Getting the information back from the jobs
Get-Job | Receive-Job|Write-Host