PowerShell functions that return true/false
You can use return statements in PowerShell:
Function Do-Something { $return = Test-Path c:\dev\test.txt return $return}Function OnlyTrue { if (Do-Something) { "Success" } else { "Fail" }}OnlyTrue
The output is Success
if the file exists and Fail
if it doesn't.
One caveat is that PowerShell functions return everything that's not captured. For instance, if I change the code of Do-Something to:
Function Do-Something { "Hello" $return = Test-Path c:\dev\test.txt return $return}
Then the return will always be Success, because even when the file does not exist, the Do-Something function returns an object array of ("Hello", False). Have a look in Boolean Values and Operators for more information on booleans in PowerShell.
Don't use True or False, instead use $true or $false
function SuccessConnectToDB { param([string]$constr) $successConnect = .\psql -c 'Select version();' $constr if ($successConnect) { return $true; } return $false;}
Then call it in a nice clean way:
if (!(SuccessConnectToDB($connstr)) { exit # "Failure Connecting"}
You'd do something like this. The Test command uses the automatic variable '$?'. It returns true/false if the last command completed successfully (see the about_Automatic_Variables topic for more information):
Function Test-Something { Do-Something $? } Function OnlyTrue { if(Test-Something) { ... } }