如何并行执行几次PowerShell函数? [英] How to execute a PowerShell function several times in parallel?
问题描述
我不确定是否需要多线程,基于作业或异步的调用,但是基本上我有一个Powershell脚本函数,该函数需要多个参数,而我需要使用不同的参数多次调用它,并且让它们并行运行.
I'm not sure whether to call this a need for multi-threading, job-based, or async, but basically I have a Powershell script function that takes several parameters and I need to call it several times with different parameters and have these run in parallel.
当前,我这样调用函数:
Currently, I call the function like this:
Execute "param1" "param2" "param3" "param4"
我如何多次调用此方法,而不必等待每次执行调用返回给调用者?
How can I call this multiple times without waiting for each call to Execute return to the caller?
当前我正在运行v2.0,但如有必要,我可以进行更新
Currently I'm running v2.0 but I can update if necessary
编辑:这是到目前为止我无法使用的内容:
here's what I have so far, which doesn't work:
$cmd = {
param($vmxFilePath,$machineName,$username,$password,$scriptTpath,$scriptFile,$uacDismissScript,$snapshotName)
Execute $vmxFilePath $machineName $username $password $scriptTpath $scriptFile $uacDismissScript $snapshotName
}
Start-Job -ScriptBlock $cmd -ArgumentList $vmxFilePath, $machineName, $username $password, $scriptTpath, $scriptFile, $uacDismissScript, $snapshotName
我得到一个错误:
无法将'system.object []'转换为参数'initializationscript'所需的'system.management.automation.scriptblock'类型.不支持指定的方法
cannot convert 'system.object[]' to the type 'system.management.automation.scriptblock' required by parameter 'initializationscript'. specified method is not supported
EDIT2 :我已经修改了脚本,但仍然收到上面提到的错误.这是我的mod:
I've modified my script but I still get the error mentioned above. Here's my mod:
$cmd = {
param($vmxFilePath,$machineName,$username,$password,$scriptTpath,$scriptFile,$uacDismissScript,$snapshotName)
Execute $vmxFilePath $machineName $username $password $scriptTpath $scriptFile $uacDismissScript $snapshotName
}
Start-Job -ScriptBlock $cmd -ArgumentList $vmxFilePath, $machineName, $username $password, $scriptTpath, $scriptFile, $uacDismissScript, $snapshotName
推荐答案
对此无需任何更新.定义一个脚本块,并根据需要使用Start-Job
多次运行该脚本块.示例:
No update necessary for this. Define a script block and use Start-Job
to run the script block as many times as necessary. Example:
$cmd = {
param($a, $b)
Write-Host $a $b
}
$foo = "foo"
1..5 | ForEach-Object {
Start-Job -ScriptBlock $cmd -ArgumentList $_, $foo
}
脚本块采用2个参数$a
和$b
,这两个参数由-ArgumentList
选项传递.在上面的示例中,分配为$_
→ $a
和$foo
→ $b
. $foo
只是可配置但静态参数的示例.
The script block takes 2 parameters $a
and $b
which are passed by the -ArgumentList
option. In the example above, the assignments are $_
→ $a
and $foo
→ $b
. $foo
is just an example for a configurable, but static parameter.
在某个时候运行Get-Job | Remove-Job
,从队列中删除完成的作业(如果要检索输出,则从Get-Job | % { Receive-Job $_.Id; Remove-Job $_.Id }
删除).
Run Get-Job | Remove-Job
at some point to remove the finished jobs from the queue (or Get-Job | % { Receive-Job $_.Id; Remove-Job $_.Id }
if you want to retrieve the output).
这篇关于如何并行执行几次PowerShell函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!