在 Powershell 中,函数的参数列表看起来像是一个数组构造函数,但有时允许 (),有时不允许,例如在调用重载的 getHashCode() 函数时。有人能解释一下这是怎么回事吗?
这是一个简单的函数和奇怪的结果:
function onBattery {
>> if ((Get-WmiObject -Class Win32_Battery | Select-Object -ExpandProperty batterystatus) -eq 2) {
>> write-output "Plugged In"
>> }
>> else {
>> write-output "On Battery"
>> }
>> }
PS C:\tmp>
PS C:\tmp> (onBattery).getHashCode
OverloadDefinitions
-------------------
int GetHashCode()
PS C:\tmp> (onBattery).getHashCode()
62670595
PS C:\tmp> onBattery($null)
Plugged In
PS C:\tmp> onBattery ($null)($null)
Plugged In
PS C:\tmp> onBattery()
At line:1 char:11
+ onBattery()
+ ~
An expression was expected after '('.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : ExpectedExpression
另外,出于好奇,如何才能使 PS 函数通过一组空括号像这样进行调用:onBattery()?