Powershell:将外部命令输出传递到另一个外部命令 [英] Powershell: Pipe external command output to another external command

查看:235
本文介绍了Powershell:将外部命令输出传递到另一个外部命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何让PowerShell理解这种类型的东西:

How can I get PowerShell to understand this type of thing:

Robocopy.exe | Find.exe "Started"

旧的命令处理器给出了结果,但是我对如何在PowerShell中执行此操作感到困惑:

The old command processor gave a result, but I'm confused about how to do this in PowerShell:

&robocopy | find.exe "Started"                #error
&robocopy | find.exe @("Started")             #error
&robocopy @("|", "find.exe","Started")        #error
&robocopy | &find @("Started")                #error
&(robocopy | find "Started")                  #error

基本上,我想将一个外部命令的输出传递给另一个外部命令.实际上,我将调用flac.exe并将其通过管道传输到lame.exe,以将FLAC转换为MP3.

Essentially I want to pipe the output of one external command into another external command. In reality I'll be calling flac.exe and piping it into lame.exe to convert FLAC to MP3.

欢呼

推荐答案

tl; dr

robocopy.exe | find.exe '"Started"'    # Note the nested quoting.

有关嵌套引用的说明,请继续阅读.

For an explanation of the nested quoting, read on.

PowerShell 确实支持往返于外部程序的管道.

PowerShell does support piping to and from external programs.

这里的问题是参数解析和传递之一: find.exe 有一个奇怪的要求,即它的搜索项必须用 literal 双引号引起来.

The problem here is one of parameter parsing and passing: find.exe has the curious requirement that its search term must be enclosed in literal double quotes.

cmd.exe中,简单的双引号就足够了:find.exe "Started"

In cmd.exe, simple double-quoting is sufficient: find.exe "Started"

相比之下, PowerShell默认情况下会在传递参数和带的引号之前预先解析参数,因此,find.exe仅看到Started没有双引号,则会导致错误.

By contrast, PowerShell by default pre-parses parameters before passing them on and strips enclosing quotes, so that find.exe sees only Started, without the double quotes, resulting in an error.

有两种解决方法:

  • PS v3 + (如果您的参数仅是 literal 和/或环境变量,则只有此选项):特殊参数--% 告诉PowerShell将命令行原样 rest 传递给目标程序(参考环境变量) (如果有),则为cmd样式(%<var>%)):
    robocopy.exe | find.exe --% "Started"

  • PS v3+ (only an option if your parameters are only literals and/or environment variables): special parameter --% tells PowerShell to pass the rest of the command line as-is to the target program (reference environment variables, if any, cmd-style (%<var>%)):
    robocopy.exe | find.exe --% "Started"

PS v2-,或者如果您需要在参数中使用PowerShell 变量:应用 PowerShell外层引用 (PowerShell将去除单引号,并将字符串的内容原样传递给find.exe,并完整地包含双引号):
robocopy.exe | find.exe '"Started"'

PS v2-, or if you need to use PowerShell variables in the parameters: apply an outer layer of PowerShell quoting (PowerShell will strip the single quotes and pass the contents of the string as-is to find.exe, with enclosing double quotes intact):
robocopy.exe | find.exe '"Started"'

这篇关于Powershell:将外部命令输出传递到另一个外部命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆