为什么powershell收集未捕获的值并将其作为数组返回 [英] Why does powershell collect uncaptured values and returns it as an array

查看:60
本文介绍了为什么powershell收集未捕获的值并将其作为数组返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码,虽然我认为应该返回单个值,但返回一个数组.

The following code, although I would think should return a single value, returns an array.

function Do-Something {
    123
    return 456
}

(Do-Something).GetType() # will say Object[]

我了解到,如果我想避免这种情况,我必须像这样将不需要的值通过管道传递给 Out-Null

I learned that if I want to avoid this I have to pipe the unwanted values to Out-Null like so

function Do-Something {
    123 | Out-Null
    return 456
}

但是,我找不到 PowerShell 以这种方式实现的任何原因.我发现如果您忘记某些东西具有您没有捕获的返回值,这可能会导致令人讨厌和无声的错误.有人可以解释一下什么时候可以派上用场吗?是否可以强制 PowerShell 不收集数组中所有未捕获的变量?

However, I couldn't find any reasoning behind why PowerShell is implemented this way. I find that this can lead to nasty and silent bugs if you forget that something has a return value that you did not capture. Could someone explain when this could come in handy? Also is it possible to force powershell not to collect all uncaptured variables in an array?

推荐答案

PowerShell 将脚本或函数中所有语句的输出发送到输出管道中,因为它是一个外壳程序,这就是外壳程序的工作方式.return 语句有点遗憾,因为函数不返回对象,而是将对象写入管道.能够终止函数的执行是必要的,但我们可能应该将其称为其他名称.简单地发出对象的能力使简单的脚本更简单,因为不需要显式的输出语句或返回.它有时会导致问题吗 - 是的,有时会.因此,对于 V5 中引入的类,我们采用了更传统的编程语言语义.如果一个类中的方法要返回一些东西,它必须声明一个返回类型并且它必须使用return语句返回一个值,否则将不返回任何内容.

PowerShell emits the output of all statements in a script or function into the output pipe because it's a shell and that's how shells work. The return statement is somewhat regrettable in that functions don't return objects, they write objects into the pipeline. Being able to terminate the execution of a function is necessary but we probably should have called it something else. The ability to simply emit objects makes simple scripts simpler because there is no need for explicit output statements or returns. Does it sometimes cause problems - yes, sometimes it does. Consequently, for classes, as introduced in V5, we went with more traditional programming language semantics. If a method in a class is going to return something, it must declare a return type and it must use the return statement to return a value, otherwise nothing will be returned.

这篇关于为什么powershell收集未捕获的值并将其作为数组返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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