Problem
You want your script or function to return data to whatever called it.
Solution
To return data from a script or function, write that data to the output pipeline:
## GetTomorrow.ps1 ## Get the date that represents tomorrow
function GetDate
{
GetDate
}
$tomorrow = (GetDate).AddDays(1) $tomorrow
Discussion
In PowerShell, any data that your function or script generates gets sent to the output pipeline, unless something captures that output. The GetDate function generates data (a date) and does not capture it, so that becomes the output of the function. The portion of the script that calls the GetDate function captures that output and then manipulates it.
Finally, the script writes the $tomorrow variable to the pipeline without capturing it, so that becomes the return value of the script itself.
Some .NET methods—such as the System.Collections.ArrayList class produce output, even though you may not expect them to. To prevent them from sending data to the output pipeline, either capture the data
or cast it to [void]: PS >$collection = NewObject System.Collections.ArrayList PS >$collection.Add("Hello") 0 PS >[void] $collection.Add("Hello")
Even with this “pipeline output becomes the return value” philosophy, PowerShell continues to support the traditional return keyword as a way to return from a function or script. If you specify anything after the keyword (such as return "Hello"), PowerShell treats that as a "Hello" statement followed by a return statement.
If you want to make your intention clear to other readers of your script, you can use the WriteOutput cmdlet to explicitly send data down the pipeline. Both produce the same result, so this is only a mat
ter of preference.
If you write a collection (such as an array or ArrayList) to the output pipeline, PowerShell in fact writes each element of that collection to the pipeline. To keep the collection intact as it travels down the pipeline, prefix it with a comma when you return it. This returns a collection (that will be unraveled) with one element: the collection you wanted to keep intact.
function WritesObjects
{ $arrayList = NewObject System.Collections.ArrayList [void] $arrayList.Add("Hello") [void] $arrayList.Add("World")
$arrayList }
function WritesArrayList
{ $arrayList = NewObject System.Collections.ArrayList [void] $arrayList.Add("Hello") [void] $arrayList.Add("World")
,$arrayList }
$objectOutput = WritesObjects
# The following command would generate an error # $objectOutput.Add("Extra")
$arrayListOutput = WritesArrayList $arrayListOutput.Add("Extra")
Although relatively uncommon in PowerShell’s world of fully structured data, you may sometimes want to use an exit code to indicate the success or failure of your script. For this, PowerShell offers the exit keyword.