JSB*_*ոգչ 13 powershell stdout return-value
在进行一些Powershell自动化时,我遇到了.cmd
自动捕获文件写入stdout的数据的问题.我有两个函数可以执行以下操作:
function a {
& external.cmd # prints "foo"
return "bar"
}
function b {
$val = a
echo $val # prints "foobar", rather than just "bar"
}
Run Code Online (Sandbox Code Playgroud)
基本上,external.cmd
发送到stdout的数据被添加到返回值a
,即使我真正想要返回的a
是我指定的字符串.我怎么能阻止这个?
Rob*_*cio 15
以下是处理此问题的几种不同方法:
捕获.cmd脚本的输出:
$output = & external.cmd # saves foo to $output so it isn't returned from the function
Run Code Online (Sandbox Code Playgroud)将输出重定向为null(扔掉)
& external.cmd | Out-Null # throws stdout away
Run Code Online (Sandbox Code Playgroud)将其重定向到文件
& external.cmd | Out-File filename.txt
Run Code Online (Sandbox Code Playgroud)通过在函数返回的对象数组中跳过它来忽略调用者
$val = a
echo $val[1] #prints second object returned from function a (foo is object 1... $val[0])
Run Code Online (Sandbox Code Playgroud)在PowerShell中,代码未捕获的任何输出值都返回给调用者(包括stdout,stderr等).所以你必须捕获或管道它不会返回一个值,或者你最终得到一个object []作为函数的返回值.
该return
关键字是真的只是为了清晰和使用PowerShell脚本块的立即退出.这样的东西甚至可以工作(不是逐字而是只是为了给你这个想法):
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
Run Code Online (Sandbox Code Playgroud)
我通常更喜欢使用以下两种技术之一,在我看来,这些技术使代码更具可读性:
将表达式转换为void以抑制返回值:
[void] (expression)
将输出值分配给$ null变量:
$null = expression
例如:
function foo
{
# do some work
return "success"
}
function bar
{
[void] (foo) # no output
$null = foo # no output
return "bar"
}
bar # outputs bar
Run Code Online (Sandbox Code Playgroud)
如果您希望命令的输出仍然打印到 powershell 命令行,您可以执行已接受答案的变体:
& external.cmd | Out-Host
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7418 次 |
最近记录: |