【问题标题】:Piping to PowerShell from CMD从 CMD 管道到 PowerShell
【发布时间】:2019-04-14 11:53:39
【问题描述】:

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

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

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

input.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,我将把它链接在一起:

tail.ps1:

Get-Content -Watch .\input.txt

process.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.exe process.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

【问题讨论】:

  • $_ != $input
  • 确实,$input 是整个管道输入对象,$_ 是正在处理的集合中的单个项目。
  • $_ 是 (PowerShell) 管道中的当前对象。但是,CMD 管道不是 PowerShell 管道,不会自动填充 $_。您需要$input 来枚举脚本的输入以实现这一点。请查看documentation

标签: powershell


【解决方案1】:

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

process.ps1

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

似乎没有访问$inputbegin{}块没有进入process{}块。

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

【讨论】:

  • process { $input } 就足够了。
  • $input 枚举脚本输入。这就是 AFAICS 在您的代码 sn-p 中填充的 $_。另请参阅我对您问题的其他评论。
最近更新 更多