问题描述
在执行一些 Powershell 自动化时,我遇到了自动捕获由 .cmd
文件写入标准输出的数据的方式.我有两个函数可以执行以下操作:
In doing some Powershell automation, I'm having trouble with the way that data written to stdout by a .cmd
file is automatically captured. I have two functions that do something like the following:
function a {
& external.cmd # prints "foo"
return "bar"
}
function b {
$val = a
echo $val # prints "foobar", rather than just "bar"
}
基本上,external.cmd
发送到 stdout 的数据被添加到 a
的返回值中,即使我真的想从 a 是我指定的字符串.我怎样才能防止这种情况?
Basically, data that
external.cmd
sends to stdout is added to the return value of a
, even though all I really want to return from a
is the string that I specified. How can I prevent this?
推荐答案
这里有几种不同的处理方法:
Here are a few different approaches for handling this:
捕获 .cmd 脚本的输出:
capture the output of the .cmd script:
$output = & external.cmd # saves foo to $output so it isn't returned from the function
将输出重定向到 null(扔掉)
redirect the output to null (throw it away)
& external.cmd | Out-Null # throws stdout away
重定向到一个文件
redirect it to a file
& external.cmd | Out-File filename.txt
通过在函数返回的对象数组中跳过它,在调用者中忽略它
ignore it in the caller by skipping it in the array of objects that's returned from the function
$val = a
echo $val[1] #prints second object returned from function a (foo is object 1... $val[0])
在 PowerShell 中,您的代码未捕获的任何输出值将返回给调用者(包括 stdout、stderr 等).因此,您必须将其捕获或通过管道传递给不返回值的对象,否则最终会以 object[] 作为函数的返回值.
In PowerShell, any output value your code does not capture is returned the caller (including stdout, stderr, etc). So you have to capture or pipe it to something that doesn't return a value, or you'll end up with an object[] as your return value from the function.
return
关键字实际上只是为了清晰和立即退出 PowerShell 中的脚本块.这样的事情甚至可以工作(不是逐字逐句,只是为了给你这个想法):
The
return
keyword is really just for clarity and immediate exit of a script block in PowerShell. Something like this would even work (not verbatim but just to give you the idea):
function foo()
{
"a"
"b"
"c"
}
PS> $bar = foo
PS> $bar.gettype()
System.Object[]
PS> $bar
a
b
c
function foobar()
{
"a"
return "b"
"c"
}
PS> $myVar = foobar
PS> $myVar
a
b
这篇关于如何避免在返回值中将数据打印到 stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!