Thursday, August 29, 2013

PowerShell - A trivial example of returning values from functions

Take a look at this simple illustration of variable scope within a function and how to return a simple value:

Function MakeNumberBigger
{
 $y++
 Write-Host "Y is $y inside the function"
 Return $y
}


$y = 10
Write-Host "Y is $y before calling function"
$x = MakeNumberBigger
Write-Host "Y is $y after calling function"
Write-Host "X is $x after being return from function"


The output will look like this:

Y is 10 before calling function
Y is 11 inside the function
Y is 10 after calling function
X is 11 after being returned from function


Showing that the changes made to Y within the function are only in-scope within that function. However, we can capture the value by returning it.

Cheers!

No comments:

Post a Comment