powershell - PowerShell函数返回行为

标签 powershell

我看到PowerShell的行为有些怪异,看来自定义函数可能需要“括号包装器”才能按您期望的方式进行评估。给定一个简单的PowerShell函数:

function Return-True { return $true }

然后是一些示例代码来调用它:
PS C:\> Return-True
True
PS C:\> Return-True -eq $false
True
PS C:\> (Return-True) -eq $false
False

有想法吗?评论?

最佳答案

当PowerShell看到 token Return-True时,会将其标识为命令,直到评估或语句结束为止,其他所有内容都是传递给函数Return-True的参数。

如果您执行以下操作,则可以看到此操作:

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

这就是为什么以下所有返回“True”的原因,因为您看到的只是带有各种参数的Return-True调用的结果:
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评估函数(不带参数)。

关于powershell - PowerShell函数返回行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/149191/

相关文章:

csv - 简单脚本似乎永远无输出运行?

powershell - $宏替换 - ExpandString 限制

powershell - 搜索时的文件扩展名

xml - 使用powershell select-object时如何使用子字符串

powershell - 如何提高Write-Progress的性能?

powershell - Appfabric Powershell 错误 "The term ' Get-CacheStatistics' 未被识别为 cmdlet 的名称。”

string - 在 PowerShell 中动态解析字符串的内容

arrays - 被困在将数据存储到数组变量中

java - Cygwin 运行的 java 版本与 windows powershell 不同

powershell - 为变量添加双引号以转义空格