[英]in powershell how do I grab command output while piping a variable into the command?
Is there a powershell cmdlet which redirects console output into a variable (NOT a file)? 是否有powershell cmdlet将控制台输出重定向到变量(不是文件)?
I need to pass the content of a variable into a binary's command line, and collect the binary's console response in another variable, but can't figure out how. 我需要将变量的内容传递给二进制文件的命令行,并在另一个变量中收集二进制文件的控制台响应,但无法弄清楚如何。
For example, Perforce's p4.exe returns an OK status with a text error message when this fails 例如,Perforce的p4.exe在失败时返回OK状态,并显示文本错误消息
$MyP4Client | p4 client -i
To abort on error I need to put a try/catch round that, then collect and check the console output from p4. 要在出错时中止,我需要进行try / catch循环,然后从p4收集并检查控制台输出。 When there's no input redirection involved, I can do this to get p4's console output into a variable:
当没有涉及输入重定向时,我可以这样做以将p4的控制台输出转换为变量:
Try {
$P4response = & 'p4' sync -f //depot/myfiles/... 2>&1
}
Catch {
ExitWithCode 1 # abort
}
if( $P4response -match "blah" ) {
# act on p4 response text
but I'm failing dismally at finding a way to both feed the $MyP4Client variable into the p4 binary then grab the output from p4. 但我没有找到一种方法将$ MyP4Client变量输入p4二进制文件然后从p4获取输出。 Among many other attempts, none of these get p4's output into $P4response :
在许多其他尝试中,这些都没有将p4的输出转换为$ P4response:
$P4response = $p4ClientSpec | & 'p4' client -i
$P4response = ( $p4ClientSpec | p4 client -i )
$P4response = { $p4ClientSpec | & 'p4' client -i }
$p4ClientSpec | & 'p4' "client -i" | $P4response
The last gets a parser error ($P4response is an expression). 最后一个得到解析器错误($ P4response是一个表达式)。 It's pretty obvious I'm missing something!
很明显我错过了什么! What's going to work, please?
请问有什么用? Thanks
谢谢
Your question implies you are trying to catch output to stderr as well as stdout. 你的问题意味着你正试图捕获输出到stderr以及stdout。 This should work:
这应该工作:
$P4response = ( $p4ClientSpec | p4 client -i 2>&1 )
You will get both the stdout and stderr from the console app in the variable, but you can separate them again quite easily: 您将从变量中的控制台应用程序获取stdout和stderr,但您可以非常轻松地将它们分开:
$output = $P4Response | Where-Object { $_.GetType() -ne [System.Management.Automation.ErrorRecord] }
$errors = $P4Response | Where-Object { $_.GetType() -eq [System.Management.Automation.ErrorRecord] }
and then you just check for non-empty $errors
. 然后你只需检查非空
$errors
。
If the executable is actually writing the error to stderr, it seems like you'd have picked it up by now with what you've already tried. 如果可执行文件实际上是将错误写入stderr,那么您现在已经尝试过将它添加到stderr中了。 If it's just writing a message directly to the console then your only option may be to use Start-Transcript to capture the console output to a file, and the parse the file contents looking for that message.
如果它只是将消息直接写入控制台,那么您唯一的选择可能是使用Start-Transcript将控制台输出捕获到文件,并解析文件内容以查找该消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.