Saturday, October 10, 2015

Powershell: how to return value from function?

Returning a value from a function is really easy in Powershell. Sometimes it is too easy if you are not careful about it. One important detail to keep in mind is that Powershell is built around placing objects on the pipe. This makes functions work differently in Powershell than it does from different languages. You are also not limited to just one return value.

Here is a minimal function:

function Test-Function
{
    "Hello World!"

Calling this places a string of "Hello World!" onto the pipe. You can catch it in a variable if you want or pipe it to some other command. The better way to do it is to use the Write-Output cmdlet. It makes it more clear as to what you are doing do debugging and troubleshooting become easier. 

function Test-Function
{
    Write-Output "Hello World!"
}

You can call Write-Output multiple times in a function to return multiple items. You could place it into a loop that runs 10 times and it will output 10 objects. I mention this because Powershell also supports the return keyword but it acts different. When a function gets to any return statement, it exits the function. 

function Test-Function
{
    return "Hello World!"
}

I prefer Write-Output over return but do use return when it is needed. 

I also want to mention that Write-Host is something that you see in scripts from time to time, but it is for host only output. So it is hard to capture into a variable and does not go into the pipe. In most cases, Write-Output is the better choice.

No comments:

Post a Comment