why is it wrong to call functions with parentheses in Powershell?
Powershell is a parsed and interpreted language. The interpreter see's parenthesis as a control structure and is not expected or required at the Call Site. Consider the following example function:
function test-function {
param
(
[string]
$string,
[string]
$word
)
"String: $string. Word: $word"
}
The proper way to call this function is as follows:
Test-Function -String "Hello" -Word "World"
The creators of Powershell at Microsoft wanted to create a single new product that would replace the cmd shell and vbscript. One of the primary goals of Powershell was to standardize cmdlet naming, call site proceedure, switch naming, and output (as an object). Anecdotally, another primary focus was eliminating the security flaws of vbscript.
By default Powershell cmdlets are Overloaded so that the same example function can be called like so:
Test-Function "Hello" "World"
Both of those examples will output the following:
"String: Hello. Word: World"
So what happens if we decide to use parenthesis at the call site?
Test-Function("Hello","World")
"String: Hello World. Word:"
So what happened? Powershell interpreted our input as a single array containing two strings which were passed to the first (positionally) variable. To get the desired result using parenthesis you'd have to do this:
Test-Function("Hello")("World")
We're sending two controlled structures (by structure think object type. In this case they're both of the type [String]
), as indicated by the parenthsis, to the function. It hits the eye wrong does it not?
I hope this helps with your understanding of why it's against the grain to use parenthesis when calling functions and cmdlets.