If-Else Conditions in Windows PowerShell Scripts

Q

How to use if-else conditions in Windows PowerShell scripts?

✍: FYIcenter.com

A

PowerShell script supports the following if-else code block to help you to perform tasks depending on logical conditions:

If (conditin1) {
   task1
} Elseif (condition2) {
   task2
   
...

} Else {
   other-task
}

Here is a sample script on how to use if-else conditions:

$h = (Get-Date).Hour
If ($h -ge 6 -and $h -lt 12) {
   "Good morning!"
} Elseif ($h -ge 12 -and $h -lt 18) {
   "Good afternoon!"
} Elseif ($h -ge 18 -and $h -lt 22) {
   "Good evening!"
} Else {
   "Why are you not sleeping!?"
}

 

Introduction of Windows PowerShell Script

⇒⇒Windows PowerShell Tutorials

2016-10-30, 354👍, 0💬