Conditional statement
if~elseif~else / switch
Conditional statement
if~elseif~else statement
$a = 1
if ($a -lt 0) {
'arg < 0'
} elseif ($a -gt 0) {
'arg > 0'
} else {
'arg = 0'
}
# arg > 0
参考:Operators
switch statement
$score = 100
switch ($score) {
{$_ -lt 70} { 'Failure'; break }
{$_ -lt 100} { 'Success'; break }
100 { 'Perfect score'; break }
Default { 'Over score' }
}
# Perfect score
Specifying parameters for switch statement
Parameters can be specified in the switch statement.
Parameters | Abbreviations | Meanings |
---|---|---|
-regex | -r | Search for matches with regular expressions |
-wildcard | -w | Search for matches with wildcards |
-exact | -e | Search for exact matches |
-casesensitive | -c | Search for case-sensitive matches |
-file | -f | Read a string from a file and evaluate it |
Example
PS> $files = "PowerShell.zip", "Windows.ZIP", "Mac.apple"
PS> $files | ForEach-Object {
>> switch -Regex -CaseSensitive ($_) {
>> "\.zip$" { "$_ is zip"; break }
>> "\.ZIP$" { "$_ is ZIP"; break }
>> Default { "$_ is Unknown file" }
>> }
>> }
>>
PowerShell.zip is zip
Windows.ZIP is ZIP
Mac.apple is Unknown file
YouTube
Click here for a video explanation.