PowerShell 中的函数返回值 [英] Function return value in PowerShell

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

问题描述

我开发了一个 PowerShell 函数,该函数执行许多涉及配置 SharePoint 团队网站的操作.最终,我希望该函数将所配置站点的 URL 作为字符串返回,因此在我的函数末尾,我有以下代码:

I have developed a PowerShell function that performs a number of actions involving provisioning SharePoint Team sites. Ultimately, I want the function to return the URL of the provisioned site as a String so at the end of my function I have the following code:

$rs = $url.ToString();
return $rs;

调用这个函数的代码如下:

The code that calls this function looks like:

$returnURL = MyFunction -param 1 ...

所以我期待一个字符串,但它不是.相反,它是 System.Management.Automation.PSMethod 类型的对象.为什么它返回该类型而不是 String 类型?

So I am expecting a String, however it's not. Instead, it is an object of type System.Management.Automation.PSMethod. Why is it returning that type instead of a String type?

推荐答案

PowerShell 具有非常古怪的返回语义 - 至少从更传统的编程角度来看是这样.有两个主要想法可以解决:

PowerShell has really wacky return semantics - at least when viewed from a more traditional programming perspective. There are two main ideas to wrap your head around:

  • 捕获并返回所有输出
  • return 关键字实际上只是表示一个逻辑退出点

因此,以下两个脚本块将有效地执行完全相同的操作:

Thus, the following two script blocks will do effectively the exact same thing:

$a = "Hello, World"
return $a

$a = "Hello, World"
$a
return

第二个示例中的 $a 变量作为管道的输出保留,并且如前所述,所有输出都被返回.事实上,在第二个示例中,您可以完全省略 return 并且您将获得相同的行为(当函数自然完成并退出时,将隐含返回).

The $a variable in the second example is left as output on the pipeline and, as mentioned, all output is returned. In fact, in the second example you could omit the return entirely and you would get the same behavior (the return would be implied as the function naturally completes and exits).

如果没有更多的函数定义,我无法说明为什么要获得 PSMethod 对象.我的猜测是,您可能有几行没有被捕获并被放置在输出管道中.

Without more of your function definition I can't say why you are getting a PSMethod object. My guess is that you probably have something a few lines up that is not being captured and is being placed on the output pipeline.

还值得注意的是,您可能不需要那些分号 - 除非您在一行中嵌套多个表达式.

It is also worth noting that you probably don't need those semicolons - unless you are nesting multiple expressions on a single line.

您可以在 about_Return 页面上阅读有关返回语义的更多信息在 TechNet 上,或通过从 PowerShell 本身调用 help return 命令.

You can read more about the return semantics on the about_Return page on TechNet, or by invoking the help return command from PowerShell itself.

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

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