PowerTip: Set a default value in a switch statement


Summary: Use the default field in switch statement to have an assumed value.

Hey, Scripting Guy! Question I was playing with Select-String and would like to have it default to a value if none was trapped for. How can I do that?

Hey, Scripting Guy! Answer Just use the Default keyword, and you can have an assumed value in the script block. In the following example, the switch is listening for the $DogSeesSquirrel object. If no values match, it returns ‘Squirrel runs free’.

switch ($dogseesquirrel)

{
'Back door' { $Response=’Bark!’}
'Couch'     { $Response=’Growl a bit.’}
'Food bowl' { $Response=’Bark! Bark! Bark!’}

Default    { $Response=’Squirrel runs free’ }
}

My apologies to our little dog for this example. 😉

The Doctor

Comments (2)

  1. PetSerAl says:

    You can move assignment out of switch statement:
    $Response = switch ($dogseesquirrel)
    {
    ‘Back door’ { ’Bark!’ }
    ‘Couch’ { ’Growl a bit.’ }
    ‘Food bowl’ { ’Bark! Bark! Bark!’ }

    Default { ’Squirrel runs free’ }
    }

    1. An excellent point about how to capture the results if they are returning a simple object!

      Although each of these are a Script Block and can perform more complex operations you are absolutely correct the results of the Scriptblocks can be captured 🙂

      Cheers!
      Sean
      Honorary Scripting Guy

Skip to main content