PowerTip: Adding a Default Exit to a PowerShell Switch

PowerTip: Adding a Default Exit to a PowerShell Switch

  • Comments 5
  • Likes

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 

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Are there other ways to exit?  I believe I tried to construct an exit just like what is shown above into a function.  The function worked, but when I called the function against a group of objects with a foreach-object loop the exit stopped the execution of the entire loop.

  • woulnt your script exit if you do that and your option isnt in the switch statement ? whats the point of that ?

  • I agree, some context would be helpful.

  • @Tay and NMayberry

    I had a script that only needed to run Tuesday-Saturday, so instead of fighting task scheduler I did:

    IF((get-date).dayofweek -match "Sunday|Monday"){exit}

    That way it would dive out if the day was sunday or monday.  A similar type of thing could be setup with a switch statement.

  • @Neil

    Thanks, that example is exactly what I needed.