Search code examples
powershellbinaryregistry

How can I use binary output in switch cases?


 $var1 = [byte]0xDB,0x01,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x01,0x02,0x04,0xF4,0x00,0x00,0x00
 $var2 = [byte]0xDB,0x01,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x01,0x00,0x03,0xF1,0x00,0x00,0x00

 $value = Get-ItemProperty -Path $path | Select-Object -ExpandProperty $name -ErrorAction SilentlyContinue

 switch ($value)
       $var1 {act1}
       $var2 {act2}

This command Get-ItemProperty -Path $path | Select-Object -ExpandProperty $name -ErrorAction SilentlyContinue outputs:

219 1 0 0 16 0 0 0 1 1 0 4 242 0 0 0

But apparently switch only works if the output in such form:

[byte]0xDB,0x01,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x01,0x00,0x03,0xF1,0x00,0x00,0x00

So I need somehow convert one of those variables for the switch to work or maybe use different commands


Solution

  • Firstly, when you pass a collection to a switch each element is evaluated separately. For example:

    switch (1,2,6) { 
        1 {"one"} 
        6 { "six"} 
        default { "default" } }
    

    outputs:

    one
    default
    six
    

    Second, the matches typically should be numbers, strings or some expression that returns a boolean, so your vars are being converted to strings. From about_switch:

    Any unquoted value that is not recognized as a number is treated as a string. To avoid confusion or unintended string conversion, you should always quote string values. Enclose any expressions in parentheses (), creating subexpressions, to ensure that the expression is evaluated correctly.

    So, if you just convert your input to a string, it should work:

    switch ("$value")
    {
       "$var1" {act1}
       "$var2" {act2}
    }