Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell functions that return true/false

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...
 }
like image 662
scapegoat17 Avatar asked Aug 09 '13 14:08

scapegoat17


People also ask

How do I return a Boolean value in PowerShell?

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.

Can a PowerShell function return a 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.

Does PowerShell have Boolean?

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.


1 Answers

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"
}
like image 123
Jeremy Thompson Avatar answered Oct 09 '22 11:10

Jeremy Thompson