首页 > 解决方案 > 从 CMD 管道到 PowerShell

问题描述

TLDR:为什么我不能在两个 POWERSHELL.exe 实例之间通过管道传输流输出?

我想跟踪一个input.txt文件并将其内容通过管道传输到任何接受 STDIN 的 CLI。使用者可能是 PowerShell.exe、php.exe、awk、python、sed 等。

我的假设是 STDIN 和 STDOUT 是所有 CLI 都说的通用概念,因此我应该能够愉快地从 CMD/DOS 命令到/从 POWERSHELL.exe 进行管道传输。

输入.txt:

hello
world

我想要的操作模式是,当添加行时,input.txt它们会立即通过管道传输到接受 STDIN 的 CLI。在 PowerShell 中,这可以模拟为:

Get-Content -Wait input.txt | ForEach-Object {$_}

除了在这里无关紧要的额外换行符之外,它可以按我的意愿工作:

hello
world

I'm adding lines and saving and...

...they appear here...

yaaaay

现在,我将这个尾部功能封装为tail.ps1,然后制作一个简单的消费者脚本process.ps1,我将把它链接在一起:

尾巴.ps1:

Get-Content -Watch .\input.txt

进程.ps1:

process {
   $_
}

我明确使用process{}块,因为我想要流式管道而不是一些end{}块循环。

同样,这在 PowerShell Shell 中起作用:

PS> .\tail.ps1 | .\process.ps1
hello
world

here is a new line saved to input.txt

现在我想将这些脚本中的每一个视为可以从 CMD / DOS 调用的单独 CLI:

C:\>POWERSHELL -f tail.ps1 | POWERShell -f process.ps1

这不起作用 - 不产生任何输出,我的问题是为什么不?

也只是将一些输入管道传输到 powershell.exeprocess.ps1不会产生输出:

C:\>type input.txt | POWERSHELL -f process.ps1

但是,从 PowerShell 到 AWK 的管道确实有效:

C:\>POWERSHELL -f tail.ps1 | awk /e/
Hello
here is a newline with an e
so we're good

为什么 AWK 接受管道但POWERShell process.ps1不接受?

另一个从 CMD/DOS 运行的令人费解的例子:

C:\>powershell -c "'hello';'world'"
hello
world       << This is as it should be
C:\>powershell -c "'hello';'world'"  | powershell -f process.ps1
            << No output appears - why not!?
W:\other>powershell -c "'hello';'world'"  | powershell -c "$input"
hello
world       << Powershell does get the stdin

标签: powershell

解决方案


我有一个解决方法,虽然我还没有解释,但它可以很好地流式传输:

进程.ps1

begin {if($input){}}
process {
    $_
}

似乎没有begin{}访问$input任何process{}块的块被输入。

这很可能是一个 PowerShell 错误,因为它在 powershell 中正常运行。


推荐阅读