Bool Value Check with IF Statement and Where Object in PowerShell

In PowerShell script, we often use logic to check some value is true or false. In normal case we may need to check if a value is true or not with If statement and in some other cases we may required to compare bool value property in Where object to filter array of values based on some Boolean value attribute.

Bool Check in If Statement

Example 1:

$a = 10; $b = 5;
$result = ($a -gt $b);
if($result -eq $true) {
  Write-Host -ForegroundColor GREEN "TRUE"
} else {
  Write-Host -ForegroundColor RED   "FALSE"
}

Example 2:

$a = 10; $b = 5;
$result = ($a -gt $b);
if($result) {
  Write-Host -ForegroundColor GREEN "TRUE"
}

Example 3: Inverse bool check

$a = 10; $b = 5;
$result = ($a -lt $b);
if(-not ($result))  {
  Write-Host -ForegroundColor GREEN "TRUE"
}

Boolean Check in Where Object Filter

Example 1:

$Result=@() 
1..25 | ForEach-Object {
$Result += New-Object PSObject -property @{ 
ID = $_
Status = if (-not($_ % 2)){$true} else {$false}
}}

// Example 1:
$Result | Where {$_.Status -eq $true}

// Example 2:
$Result | Where {$_.Status}

// Example 3: Inverse boolean check
$Result | Where {-not ($_.Status)}

Advertisement

Leave a Comment