将字符串通过管道传输到cmd在PowerShell脚本中不起作用 [英] Piping a string into a cmd does not work in PowerShell script

查看:20
本文介绍了将字符串通过管道传输到cmd在PowerShell脚本中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我直接在PowerShell窗口中执行它时,我有以下工作调用:

$myexe = "C:MyExe.exe"
"MyString" | & $myexe // works
Write-Output "MyString" | & $myexe // seems to work too
但是,当我在PowerShell脚本的函数中执行相同的操作时,它不再起作用。程序未收到字符串...有什么想法吗?

与与推荐答案兼容的外壳程序(如)不同,PowerShell不会自动将给定脚本或函数接收的管道输入转发到从该脚本或函数内部调用的命令。

为此,必须使用automatic $input variable[1]

例如:

function foo {
  # Relay the pipeline input received by this function 
  # to an external program, using `cat` as an example.
  $input | & /bin/cat -n # append $args to pass options through
}

'MyString' | foo

请注意,在这种情况下,&是可选的,因为/bin/cat是无引号的文字路径-有关&是必需的的信息,请参阅this answer

输出(在类Unix平台上)为: 1 MyString,这表明cat实用程序通过其stdin接收了foo函数自己的管道输入,这要归功于$input

如果没有管道$inputcat,后者将根本不会收到标准输入(在cat的情况下,将阻止,等待交互输入)。

如果您希望支持传递文件名参数-代替管道输入-则需要做更多工作:

function foo {
  if ($MyInvocation.ExpectingInput) { # Pipeline input present
    # Relay the pipeline input received by this function 
    # to an external program, using `cat` as an example.
    $input | /bin/cat -n $args
  } else { # NO pipeline input.
    /bin/cat -n $args
  }
}

'MyString' | foo  # pipeline input
foo file.txt      # filename argument

注意:

  • 只有-advanced functions and scripts可以使用$input变量,它的使用意味着所有通过管道输送到封闭函数/脚本的输入在开始发送前全部收集

  • 要真正将脚本/函数自己的管道输入到外部程序的单个调用,即在脚本/函数接收输入时将转发-需要直接使用.NET APISystem.Diagnostics.Process


同样,需要$input通过PowerShell的CLI外部访问通过管道传输到PowerShell命令的数据;例如,从bash
echo hi | pwsh -c '$input | ForEach-Object { "[{0}]" -f $_ }'

这篇关于将字符串通过管道传输到cmd在PowerShell脚本中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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