If conditional shorthand

suggest change

if can test a value directly. $false, $null, 0, and an empty string are false. Any other non-empty string is true, including the string 'false'. This example was checked on Windows PowerShell 2.0.

# Checked on Windows PowerShell 2.0 
$boolean = $false;
$string = "false";
$emptyString = "";

If($boolean){
    # this does not run because $boolean is false
    Write-Host "Shorthand If conditions can be nice, just make sure they are always boolean."
}

If($string){
    # This does run because the string is non-zero length
    Write-Host "If the variable is not strictly null or Boolean false, it will evaluate to true as it is an object or string with length greater than 0."
}

If($emptyString){
    # This does not run because the string is zero-length
    Write-Host "Checking empty strings can be useful as well."
}

If($null){
    # This does not run because the condition is null
    Write-Host "Checking Nulls will not print this statement."
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents