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"


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


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

$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'}


the variable is 2


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

THANK YOU for your review!

Publication: 2022-05-02 from Bernhard 🔔

Top articles in this section

PowerShell Log-Files: Logging into a textfile - write to file
Log files in PowerShell can be created via the Out-File command, via a custom function, or via PowerShell's built-in Transcript.

PowerShell Loops and Array
An array stores multiple values, similar to a 2-column table.

PowerShell text file and csv read / write
PowerShell text file and csv read / write

Questions / Comments