PowerShell if else and switch

 

Test conditions with the commands if, elseif, else and switch and execute a command if they apply: if, else, ... then

if - elseif - else


In the following example the variable $input is tested for certain values, if none of the values match else is used: 

$input=4 #input is set with the value 4
 
if ($input -eq '1') { #Test if the variable Input is equal to 1. If it is not, the following command will not be executed:
        write-host 'the variable input=1' #The command if input equals 1: write the variable input=1
    } elseif ($input -eq '2') { #Test if input is equal to 2. Does not match
        write-host 'the variable input=2' { elseif ($input -eq '2')
    } elseif ($input -eq '3') {#Test if input is equal to 3: Not true
        write-host 'the variable input=3' } #if no input is equal to 3
    } else {#if none of the conditions match, continue with the following script block
        write-host 'the variable is neither 1 nor 2 nor 3'#command:write "the variable is neither 1 nor 2 nor 3"
    }

Output

the variable is neither 1 nor 2 nor 3
PS C:\WINDOWS\system32> 

switch

In case of multiple if- elseif queries, the switch command can be used:

$Input=2
$Detail = Switch($Input) {
    0 {'the variable is 0'}
    1 {'the variable is 1'}
    2 {'the variable is 2'}
    3 {'the variable is 3'}
    4 {'the variable is 4'}
}
$Detail

Output:

the variable is 2

 

positive Bewertung({{pro_count}})
Rate Post:
{{percentage}} % positive
negative Bewertung({{con_count}})

THANK YOU for your review!

Questions / Comments


By continuing to browse the site, you agree to our use of cookies. More Details