Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Thursday, April 21, 2011

How to return data from a PowerShell function

Functions allow us to modularize our scripts and reuse code over and over again.  In some cases, you may want PowerShell to return information back to the parent scope so it can continue to be used.  Below is a very simple function.

Function DoMath
{
   
$a = 5 + 5
  

}
 DoMath


When we call this function, it returns our data.  We can set it up to return the data to a variable by calling the function with this command:

 $a = DoMath


The Return keyword is available. Return acts as a break for the function.  It will return the data specified, and stop processing the rest of the function.


Function DoMath
{
   
 $a = + 5
    Return
   Write-Host $a
}
 DoMath 

Even though there is a Write-Host statement, the Return keyword prevents its execution.

No comments: