PowerShell if else and switch

Diese Seite gibt es auch in Deutsch

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!


Top articles in this section

PowerShell Log-Files: Logging into a textfile - write to file

PowerShell Log-Files: Logging into a textfile - write to file

created: 2022-05-05 from Bernhard

Log files in PowerShell can be created via the Out-File command, via a custom function, or via PowerShell's built-in Transcript. ... continue reading

PowerShell Loops and Array

PowerShell Loops and Array

created: 2022-05-02 from Bernhard

An array stores multiple values, similar to a 2-column table. ... continue reading

Preview PowerShell text file and csv read / write

PowerShell text file and csv read / write

created: 2022-05-02 from Bernhard

PowerShell text file and csv read / write ... continue reading


Questions / Comments