Wednesday, June 20, 2018

Function-call-like parentheses in PowerShell cmdlet invocations will probably not do what you expect

One user tried to do something along these lines to call a function in PowerShell and pass the result as a parameter to a cmdlet:

Do-Thing -Information SomeFunc($abc)

This is an entirely reasonable thing to try, but PowerShell interprets it in a surprising way. First, it tries to be helpful by interpreting SomeFunc as a string literal. PowerShell function calls (distinct from calling .NET functions form PowerShell) don't use parentheses. In this case, PowerShell treats the parentheses as separating the $abc argument from SomeFunc, so the string "SomeFunc" becomes the value for the -Information switch and $abc, being unaffiliated with a switch, becomes a positional parameter. Usually this will result in error messages about a value not being suitable for any positional parameter.

To make PowerShell do what you likely wanted, wrap the entire function call in parentheses:

Do-Thing -Information (SomeFunc $abc)

No comments:

Post a Comment