gpt4 book ai didi

powershell - PowerShell函数返回行为

转载 作者:行者123 更新时间:2023-12-03 13:43:31 24 4
gpt4 key购买 nike

我看到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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com