PowerTip: Adding a Default Exit to a PowerShell Switch

Summary: Learn how to add a default exit condition to a Windows PowerShell switch statement to control execution of commands.


Hey, Scripting Guy! QuestionI have the following switch statement, and I want to prevent the line Write-Host “switched” from executing? How can I do this?

$a = 3

switch ($a) {

 1 { “one detected” }

 2 { “two detected” }

}

Write-Host “switched”

Hey, Scripting Guy! Answer Add an exit statement to the default switch as shown here:

$a = 3

switch ($a) {

1 { “one detected” }

2 { “two detected”}

DEFAULT { exit}

}

Write-Host “switched