如何 运行 PowerShell 管道并行处理?

How can I run PowerShell pipeline processes in parallel?

当 运行ning 在 PowerShell 管道中处理时,下一个进程只会在前一个进程退出后启动。这是一个简单的演示命令:

python -c "from time import *; print(time()); sleep(3)" | python -c "from time import *; print(input()); print(time())"

这将打印如下内容:

1599497759.5275168
1599497762.5317411

(注意时间间隔3秒)

有什么方法可以使进程 运行 并行吗?寻找适用于 Windows PowerShell 或 Windows.

上的 PowerShell Core 的解决方案

我找到了 ,但它只处理 cmdlet,不处理普通的可执行文件。

这可能是 PowerShell 的本机命令处理器在将其绑定到下游命令之前等待查看是否写入更多输出。

显式刷新输出似乎有效(在 Ubuntu 20.04 上使用 Python 3.8 和 PowerShell 7.0.1 进行测试):

python3 -c "from time import *; print(time(), flush=True); sleep(3)" | python3 -c "from time import *; print(input()); print(time())"

在 2 毫秒内给我时间戳

在 Windows 上,flush=True 选项似乎无法缓解问题,但将第二个命令包装在 ForEach-Object 中可以:

python3 -c "from time import *; print(time(), flush=True); sleep(3)" |ForEach-Object { $_|python3 -c "from time import *; print(input()); print(time())" }

在 PowerShell 中使用管道是关于将对象流从一个同步命令传递到另一个同步命令,而不是异步处理。

如果您只想并发处理,可以使用作业。

您没有指明您使用的是哪个版本的 PowerShell,所以我假设只是 Windows PowerShell。

# Create your script block of code you want to execute in each thread/job
$ScriptBlock = {
    python -c "from time import *; print(time()); sleep(3)"
}

# A trivial example demonstrating that we can create 5 jobs to execute the same script block
$Jobs = 1..5 | ForEach-Object {
    Start-Job -ScriptBlock $ScriptBlock
}

# Wait for jobs to finish executing
Wait-Job $Jobs

# Receive the output data stream from all jobs
Get-Job $Jobs | Receive-Job

about_Jobs 帮助主题中阅读有关职位的更多信息:

Get-Help about_Jobs

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_jobs?view=powershell-5.1

嗯,如果你want/need使用管道,我建议使用

ForEach-Object -Parallel

PowerShell ForEach-Object Parallel Feature

或者您也可以使用

workflow paralleltest {

 parallel {

  python -c "from time import *; print(time()); sleep(3)" | python -c "from time import *; print(input()); print(time())"

  }

PowerShell Workflows