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")
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 ;)
If ($Result)
{
"function returned true"
}
else
{
"function returned false"
}
man your article solved my puzzle Thanks for publishing this, Its really helpful.
ReplyDeleteHey no problem :)
ReplyDeleteThank you, solved my problem, I didn't realize you needed the $ before true/false
ReplyDeleteComing from strongly typed languages this is foreign to me :)
Mate, even after 9 years this is helping people. Cheers to that.
ReplyDelete