August 16th, 2012

PowerTip: Adding a Default Exit to a PowerShell Switch

Doctor Scripto
Scripter

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 

Author

The "Scripting Guys" is a historical title passed from scripter to scripter. The current revision has morphed into our good friend Doctor Scripto who has been with us since the very beginning.

0 comments

Discussion are closed.