Switch - Does the same as the if statement with the exception that it can evaluate multiple comparisons, each having the ability to execute code blocks. This is the same as a "select case" or "case" statements in VBScript and other programming languages
Using the Switch Statement for Multiple Comparisons Since we can use elseif statements to test multiple conditions, there may come a time when too many additional tests lend to difficult script writing and down-right ugliness. There are other times where you want to test multiple conditions that result in multiple True values and you don't want the script to stop testing when it receives the first Truevalue (as it does with an if statement). The option that allows you to accomplish this is the switch statement. The PowerShell switch statement organizes a collection of tests that are evaluated using the same expression. The Switch statement syntax:
switch (expression) { (test) {code block} value {code block} default {code block} }
* Test = An evaluated expression.
* Value = A value, like a number or text string.
* Default = Default code block to run if none of the expressions return a True value.
Here is an example from Ed Wilson's PowerShell book: "Windows PowerShell Step by Step." Save the script code as ComputerRoles.ps1 and run the script:
Example
$objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2"
"Computer "+ $objWMI.name + " is a: "
switch ($objWMI.domainRole)
{
0 {Write-Host "Stand alone workstation"}
1 {Write-Host "Member workstation"}
2 {Write-Host "Stand alone server"}
3 {Write-Host "Member server"}
4 {Write-Host "Back-up domain controller"}
5 {Write-Host "Primary domain controller"}
default {Write-Host "The role can not be determined"}
}
Example
$strComputer = Read-Host "Enter Computer Name"
$objWMI = Get-WmiObject -Class win32_ComputerSystem -namespace "root\CIMV2" `
-computername $strComputer
Write-Host "Computer: $strComputer is a:"
switch ($objWMI.domainRole)
{
0 {Write-Host "Stand alone workstation"}
1 {Write-Host "Member workstation"}
2 {Write-Host "Stand alone server"}
3 {Write-Host "Member server"}
4 {Write-Host "Back-up domain controller"}
5 {Write-Host "Primary domain controller"}
default {Write-Host "The role can not be determined"}
}
Example
switch (10)
{
(1 + 9) {Write-Host "Congratulations, you applied addition correctly"}
(1 + 10) {Write-Host "This script block better not run"}
(11 - 1) {Write-Host "Congratulations, you found the difference correctly"}
(1 - 11) {Write-Host "This script block better not run"}
}
Conditional logic is the foundation for dynamic PowerShell script writing. We successfully demonstrated how we can control the flow of a script base on conditional responses. In the next PowerShell training session we are going to build on what we have learned and introduce Loops,