我有一个powershell脚本,可以对一堆图像进行批处理,我想做一些并行处理。Powershell似乎有一些后台处理选项,如启动作业、等待作业等,但我发现用于并行工作的唯一好资源是编写脚本文本并运行这些选项(PowerShell Multithreading)。
理想情况下,我希望在.net 4中实现类似于并行foreach的功能。
一些看起来不太像的东西:
foreach-parallel -threads 4 ($file in (Get-ChildItem $dir))
{
.. Do Work
}
也许我直接去c#会更好。
发布于 2010-10-26 00:56:02
您可以使用Background Jobs在Powershell2中执行并行作业。查看Start-Job和其他作业cmdlet。
# Loop through the server list
Get-Content "ServerList.txt" | %{
# Define what each job does
$ScriptBlock = {
param($pipelinePassIn)
Test-Path "\\$pipelinePassIn\c`$\Something"
Start-Sleep 60
}
# Execute the jobs in parallel
Start-Job $ScriptBlock -ArgumentList $_
}
Get-Job
# Wait for it all to complete
While (Get-Job -State "Running")
{
Start-Sleep 10
}
# Getting the information back from the jobs
Get-Job | Receive-Job
发布于 2013-03-02 00:43:00
http://gallery.technet.microsoft.com/scriptcenter/Invoke-Async-Allows-you-to-83b0c9f0
我创建了一个invoke-async,它允许你同时运行多个脚本块/cmdlet/函数。这对于小作业(100台机器上的子网扫描或wmi查询)非常有用,因为创建运行空间的开销与start-job的启动时间的开销是相当大的。它可以像这样使用。
使用scriptblock,
$sb = [scriptblock] {param($system) gwmi win32_operatingsystem -ComputerName $system | select csname,caption}
$servers = Get-Content servers.txt
$rtn = Invoke-Async -Set $server -SetParam system -ScriptBlock $sb
仅cmdlet/函数
$servers = Get-Content servers.txt
$rtn = Invoke-Async -Set $servers -SetParam computername -Params @{count=1} -Cmdlet Test-Connection -ThreadCount 50
发布于 2010-10-26 03:59:06
背景作业的设置成本很高,并且不可重复使用。PowerShell MVP Oisin Grehan拥有PowerShell多线程的a good example。
(10/25/2010网站已关闭,但可通过Web Archive访问)。
我在下面的数据加载例程中使用了经过调整的Oisin脚本:
http://rsdd.codeplex.com/SourceControl/changeset/view/a6cd657ea2be#Invoke-RSDDThreaded.ps1
https://stackoverflow.com/questions/4016451
复制相似问题