Kae Travis

Passing Multiple Arguments to a PowerShell Function

Tags:

Passing multiple arguments to a PowerShell function can be slightly confusing, especially if coming from a VBScript background.

You see, when calling a VBScript function with multiple arguments you specify a comma in between the arguments when you call the function like so:

Function test(arg1, arg2)
wscript.echo arg1 & " and " & arg2
End Function
test "one","two"
'output
'one and two

However, if we did the equivalent in PowerShell we would see the following:

Function test($arg1, $arg2) {
write-host "$arg1 and $arg2"
}
test "one","two"
#output
#one two and

This is because what we are essentially doing here is passing one argument as $arg1 (a system.object[] array containing “one” and “two”) and $null (nothing!) for $arg2! When we use commas in PowerShell, it converts the value into a System.Object[] array.

As an example, run this:

$testvariable = "one","two"
write-host $testvariable.GetType()
#output
#System.Object[]

The simple fix is simply to omit the comma when calling the function like so:

Function test($arg1, $arg2) {
write-host "$arg1 and $arg2"
}
test "one" "two"
#output
#one and two
Passing Multiple Arguments to a PowerShell Function
Passing Multiple Arguments to a PowerShell Function

Leave a Reply