powershell - Parsing of "case" constants in Switch statements does not make sense -
can explain me behaviour of second switch statement in code:
function weird() { $l_ret= [system.windows.forms.dialogresult]::abort "begin switch ok" switch( $l_ret ) { ([system.windows.forms.dialogresult]::abort) { 'abort' } ([system.windows.forms.dialogresult]::cancel) { 'cancel' } } "end switch ok" "begin switch bad" switch( $l_ret ) { [system.windows.forms.dialogresult]::abort { 'abort' } [system.windows.forms.dialogresult]::cancel { 'cancel' } } "end switch bad" }
if invoke weird
, get:
begin switch ok abort end switch ok begin switch bad end switch bad
but expect is:
begin switch ok abort end switch ok begin switch bad abort end switch bad
[edited clearer i'm asking] in other words, kind of parsing mode in when parsing case values not recognize typed enum constants???
thanks.
edit: keith's second-to-last comment in checked answer below "answer". other comments useful. thanks.
as bruce mentions, need add parens around type specifier in bad switch e.g.:
function weird() { $l_ret= [system.windows.forms.dialogresult]::abort "begin switch ok" switch( $l_ret ) { ([system.windows.forms.dialogresult]::abort) { 'abort' } ([system.windows.forms.dialogresult]::cancel) { 'cancel' } } "end switch ok" "begin switch bad" switch( $l_ret ) { ([system.windows.forms.dialogresult]::abort) { 'abort' } ([system.windows.forms.dialogresult]::cancel) { 'cancel' } } "end switch bad" }
otherwise powershell interprets information string , not type specifier. operates way switching on simple string tokens is, well, simple e.g.:
$var = "bar" switch ($var) { foo { "foo" } bar { "bar" } }
it typical switch statements operate on literal values instead of expressions. powershell allows use expressions typically specify expressions scriptblock {...}
. appears powershell accepts parens (evals expression literal match). inline powershell's command parsing mode.
fwiw note on switch bit misleading:
followed { "string"|number|variable|{ expression } { statementlist } default { statementlist } }
this seem indicate string literals must quoted when don't need be. well, except when string contains spaces or other punctuation {
, ;
, etc.
btw shortened version works:
switch( $l_ret ) { abort { 'abort' } cancel { 'cancel' } }
powershell knows how coerce field name of enum enum type if knows expected enum type is. unfortunate powershell can't that, @ least in case, specified name.
Comments
Post a Comment