In Powershell it looks like the parameter list to a function is an array constructor, but sometimes () is allowed and sometimes not, for instance when calling the overloaded getHashCode() function. Can someone explain what's going on with that ?
Here is a simple function and the curious results:
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
Also, out of curiosity what would it take to make a PS function be callable via an empty set of parenthesis like this: onBattery()?
I'd suggest this might be more of a question for Stackoverflow than SF, however...
getHashCode()
that you reference is a "method" NOT a "function". While similar in many ways they're not the same.I believe the main difference being that functions can be completely independant, eg they CAN have parameters passed to them but that's not required. Methods are associated to an object, so do require something to be passed to them.
You may have seen other types of methods out there, for instance GetType() is a method not a function.
Since it's a function, you could simply call it as
onBattery
with nothing else.More detailed info can be found here: https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function