I am pretty new with using PowerShell and was wondering if anyone would have any input on trying to get PowerShell functions to return values.
I want to create some function that will return a value:
Function Something
{
# Do a PowerShell cmd here: if the command succeeded, return true
# If not, then return false
}
Then have a second function that will only run if the above function is true:
Function OnlyTrue
{
# Do a PowerShell cmd here...
}
Test-Connection command. Some command returns the value but not the Boolean value but they support parameter which returns the Boolean value. For example, the Test-Connection command uses -Quiet parameter to return a Boolean value.
Because we can return values from a PowerShell function, the value of the return keyword might not immediately be evident. The difference between returning values with Write-Output and the return keyword is using the return keyword exits the current scope.
PowerShell can implicitly treat any type as a Boolean. It is important to understand the rules that PowerShell uses to convert other types to Boolean values.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With