Besides you can use if statement to evaluate multiple conditions, you can also use switch statement. The switch statement list each condition and optional action. When a condition is met, the action is performed.
Basic switch syntax:
Switch (condition)
{
<condition> : {action}
<condition> : {action}
<default> : {action}
}
Let's review about if statement.
"======================"
"Day in a week : "
"Mon : Monday"
"Tue : Tuesday"
"Wed : Wednesday"
"Thu : Thursday"
"Fri : Friday"
"Sat : Saturday"
"Sun : Sunday"
"======================="
$input = Read-Host 'Your input (Mon, Tue, Wed, Thu, Fri, Sat, Sun)'
if ($input -eq 'Mon') {
Write-Host ("It's Monday!")
} elseif ($input -eq 'Tue') {
Write-Host ("It's Tuesday!")
} elseif ($input -eq 'Wed') {
Write-Host ("It's Wednesday!")
} elseif ($input -eq 'Thu') {
Write-Host ("It's Thursday!")
} elseif ($input -eq 'Fri') {
Write-Host ("It's Friday!")
} elseif ($input -eq 'Sat') {
Write-Host ("It's Saturday!")
} elseif ($input -eq 'Sun') {
Write-Host ("It's Sunday!")
} else {
Write-Host ("None of above!")
}
Instead of if statement here's what you can do with switch statement.
$input = Read-Host 'Your input (Mon, Tue, Wed, Thu, Fri, Sat, Sun)'
Switch ($input)
{
"Mon" { Write-Host ("It's Monday!") }
"Tue" { Write-Host ("It's Tuesday!") }
"Wed" { Write-Host ("It's Wednesday!") }
"Thu" { Write-Host ("It's Thursday!") }
"Fri" { Write-Host ("It's Friday!") }
"Sat" { Write-Host ("It's Saturday!") }
"Sun" { Write-Host ("It's Sunday!") }
default { Write-Host ("None of above!") }
}
You can also do this with switch.
Switch ($input = Read-Host 'Your input (Mon, Tue, Wed, Thu, Fri, Sat, Sun)')
{
"Mon" { Write-Host ("It's Monday!") }
"Tue" { Write-Host ("It's Tuesday!") }
"Wed" { Write-Host ("It's Wednesday!") }
"Thu" { Write-Host ("It's Thursday!") }
"Fri" { Write-Host ("It's Friday!") }
"Sat" { Write-Host ("It's Saturday!") }
"Sun" { Write-Host ("It's Sunday!") }
default { Write-Host ("None of above!") }
}
Like this too.
Write-Host ($result = switch($input = Read-Host 'Your input (Mon, Tue, Wed, Thu, Fri, Sat, Sun)') {
"Mon" { "It's Monday!" }
"Tue" { "It's Tuesday!" }
"Wed" { "It's Wednesday!" }
"Thu" { "It's Thursday!" }
"Fri" { "It's Friday!" }
"Sat" { "It's Saturday!" }
"Sun" { "It's Sunday!" }
default { "None of above!" }
})
Switch also can handles arrays, it will process each element in array collection.
$days = @('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
Switch ($days) {
"Mon" { "It's Monday!" }
"Tue" { "It's Tuesday!" }
"Wed" { "It's Wednesday!" }
"Thu" { "It's Thursday!" }
"Fri" { "It's Friday!" }
"Sat" { "It's Saturday!" }
"Sun" { "It's Sunday!" }
default { "None of above!" }
}
Thank you, please share if you think this is worth :)
ReplyDelete