#powershell: Fun with Switch Statement Part 2

../continue

switch ($d) { { “default” } { “d” } { “others” } { “o” } }
#
$d = “Default”
$d = “others
#
d
o

Basically, the odd script blocks {namely “default” and “others”} are the actual criteria to be tested in the #powershell switch block. In this instance, there is essentially nothing to check for hence whatever criterion given to the switch block will always be deemed as valid matches regardless of values or object types.

Unless each incoming object needs to be processed and not just a “simple” match, represented by the special $_ variable, …

… the curly brackets are not required i.e.

switch ($d) { “default” { “d” } “others” { “o” } }

Otherwise they are mandatory:

switch ($d) { { $_ -notlike “default” } { “d” } “others” { “o” } }

failing which will provoke an error:

switch ($d) { $_ -notlike “default” { “d” } “others” { “o” } }
At line:1 char:17
+ switch ($d) { $_ -notlike “default” { “d” } “others” { “o” } }
+ ~
Missing statement block in switch statement clause.
At line:1 char:26
+ switch ($d) { $_ -notlike “default” { “d” } “others” { “o” } }
+ ~
Missing statement block in switch statement clause.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingSwitchStatementClause

Incidentally, it is a good practice to end each script block with the break keyword to avoid unforeseen fall-through matches.

Bookmark the permalink.

Leave a Reply