Saturday, October 10, 2015

Powershell: how to call a function?

Sometimes it is the simplest thing that can be the most frustrating when learning a new language. Calling a custom function in Powershell can be one of those if you come from a different language. If you are having an issue with this, you have come to the right place. You are probably looking at something like this and wondering why it wont work:

TestFunction($Name, $Count)

If your coming from another language, this looks like it would be perfectly normal. The gotcha in Powershell is that the coma and the parenthesis are not needed here for a function call and actually mean something else. In this example it defines an array.
Before I go any further, let's define TestFunction:

function TestFunction ($name, $count)
    Write-Output "Name is '$name' and Count is '$count'"

It is a simple function that takes two parameters. While this works as a function and looks like something you know, let's do it the Powershell way:

function TestFunction
    param($name, $count)

    Write-Output "Name is '$name' and Count is '$count'"

So now we have a function that takes two arguments. The first argument is name and the second argument is count. Here are the correct ways to call that function:

TestFunction $Name $Count
TestFunction -name $Name -count $Count
TestFunction -name "Kevin" -count

Now that we know the correct way to make that call and know what the function looks like, I can explain why our initial call fails to work. Because it is the equivalent to this call:

$Array = ($Name,$Count)
TestFunction -name $Array -count $null

So you were basically creating an array that contained your two variables and passing it in as an array to the first argument. You were also leaving the second argument as a null value. Now that you see it, it looks like a silly thing to do. No wonder things were not working as you expected. 

No comments: