清除 Powershell 函数中捕获的输出/返回值 [英] Clear captured output/return value in a Powershell function

查看:49
本文介绍了清除 Powershell 函数中捕获的输出/返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法清除函数内部的返回值,这样我就可以保证返回值是我想要的?或者可能关闭该功能的这种行为?

Is there a way to clear the return values inside of a function so I can guarantee that the return value is what I intend? Or maybe turn off this behaviour for the function?

在这个例子中,我希望返回值是一个包含 ("Hello", "World") 的 ArrayList

In this example, I expect the return value to be an ArrayList containing ("Hello", "World")

function GetArray() 
{
    # $AutoOutputCapture = "Off" ?
    $myArray = New-Object System.Collections.ArrayList
    $myArray.Add("Hello")
    $myArray.Add("World")

    # Clear return value before returning exactly what I want?
    return $myArray
}

$x = GetArray
$x

但是,输出包含从 Add 操作中捕获的值.

However, the output contains the captured value from the Add operations.

0
1
Hello
World

我发现 Powershell 的这个功能"很烦人,因为它可以很容易地通过调用另一个函数来破坏你的函数,你不知道它返回了一个值.

I find this "feature" of Powershell very annoying because it makes it really easy to break your function just by calling another function, which you didn't know returned a value.

更新

我知道有一些方法可以防止输出被捕获(如下面的一个答案中所述),但这需要您知道函数实际上返回了一个值.如果您正在调用另一个 Powershell 函数,将来可能有人更改此函数以返回一个值,这会破坏您的代码.

I understand there are ways to prevent the output from being captured (as described in one of the answers below), but that requires you to know that a function actually returns a value. If you're calling another Powershell function, it can be, in the future, someone changes this function to return a value, which will then break your code.

推荐答案

管道输出到Out-Null,将输出重定向到$null,或者在函数调用前加上[void]:

Pipe output to Out-Null, redirect output to $null, or prefix the function calls with [void]:

$myArray.Add("Hello") | Out-Null

$myArray.Add("Hello") >$null

[void]$myArray.Add("Hello")

这篇关于清除 Powershell 函数中捕获的输出/返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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