PowerShell 函数返回行为 [英] PowerShell functions return behavior

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

问题描述

我在 PowerShell 中看到了一些相当奇怪的行为,看起来自定义函数可能需要一个括号包装器"来按照您的预期进行评估.给定一个简单的 PowerShell 函数:

I am seeing some rather weird behavior with PowerShell, it looks like custom functions might need a "parenthesis wrapper" to evaluate as you might expect them. Given a simple PowerShell function:

function Return-True { return $true }

然后是一些示例代码来调用它:

and then some sample code to invoke it:

PS C:\> Return-True
True
PS C:\> Return-True -eq $false
True
PS C:\> (Return-True) -eq $false
False

想法?注释?

推荐答案

当 PowerShell 看到标记 Return-True 时,它会将其识别为命令,直到评估或语句结束,其他一切都是传递给函数 Return-True 的参数.

When PowerShell sees the token Return-True it identifies it as a command and until evaluation or end of the statement, everything else is an argument which is passed to the function Return-True.

如果你这样做,你可以看到这个:

You can see this in action if you do:

PS > function Return-True { "The arguments are: $args"; return $true }
PS > Return-True -eq $false
The arguments are: -eq False
True

这就是为什么以下所有返回True"的原因,因为您所看到的只是使用各种参数调用 Return-True 的结果:

That's why all of the following return 'True', because all you are seeing is the result of calling Return-True with various arguments:

PS > Return-True -eq $false
True
PS > Return-True -ne $false
True
PS > Return-True -eq $true
True
PS > Return-True -ne $true
True

使用 (Return-True) 强制 PowerShell 评估函数(不带参数).

Using (Return-True) forces PowerShell to evaluate the function (with no arguments).

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

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