Most Popular Posts

Friday 16 March 2012

Return $true or $false from a Powershell function

I spent some time understanding this, especially coming from a C, .NET, vbscript background the logic behind functions in powershell just baffled me.

As you probably know the proper definition of a function is a routine that returns a value (as opposed to a sub that just runs a block of code). Well in powershell functions DO NOT return values by default (unless you use the Return keyword as shown below) and all output from within the function is shown as output in the console, very confusing to begin with....

I wanted to create a function that accepted a single parameter, $Path and then use this to:
1) determine if the path existed and create it if not
2) return either $true or $false depending on whether or not that path existed.

Here is the function I wrote after wrapping my head around this:

function CheckIfPathExistsAndCreate([string]$Path)
{
if(!(Test-Path -Path $path))
{
New-Item $path -type directory > $null
return $false
}
else
{
return $true
}
}

$Result = (CheckIfPathExistsAndCreate "C:\Dev\PShell\TestDir")

If ($Result)
{
"function returned true"
}
else
{
"function returned false"
}
As you can see the function is very simple (there is no error trapping yet!) but the key thing here to understand is that unless you direct ALL output within a function to $null (as above) then you will never be able to test the return value properly. Try removing it and see what happens, try putting it back and see what happens ;)