You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Windows PowerShell中高效且简便地并行运行命令?

Windows PowerShell无模块依赖的高效并行执行方案

针对受限于公司政策无法安装模块的Windows PowerShell用户,这里提供一种高效的并行执行替代方案。

Windows PowerShell内置的本地并行调用方案有Start-Job和workflow,但二者都以缓慢低效著称。其中workflow不仅不推荐使用,在新版本PowerShell中已经完全不可用。

另一种高效方案是借助PowerShell SDK,通过System.Management.Automation.Runspaces命名空间编写自定义并行逻辑。PowerShell Core中的ForEach-Object -Parallel以及Start-ThreadJob(PowerShell Core预装,Windows PowerShell需从PowerShell Gallery获取)都是基于该机制实现的。

以下是简单示例代码:

$throttlelimit = 3

$pool = [runspacefactory]::CreateRunspacePool(1, $throttlelimit)
$pool.Open()

$tasks = 0..10 | ForEach-Object {
    $ps = [powershell]::Create().AddScript({
        'hello world from {0}' -f [runspace]::DefaultRunspace.InstanceId
        Start-Sleep 3
    })
    $ps.RunspacePool = $pool

    @{ Instance = $ps; AsyncResult = $ps.BeginInvoke() }
}

$tasks | ForEach-Object {
    $_.Instance.EndInvoke($_.AsyncResult)
}

$tasks.Instance, $pool | ForEach-Object Dispose

不过这种方案虽然高效,但随着代码复杂度提升会变得繁琐复杂,带来不少使用疑问。那么,是否存在更简便的实现方式?

内容的提问来源于stack exchange,提问作者Santiago Squarzon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:35:25