1
 $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

4
  • Why don't you convert those byte arrays to hex strings and use those hex strings instead Commented Oct 19, 2023 at 17:30
  • 1
    On a side note, to correctly create a byte array: [byte[]] (0xDB,0x01,…). In your examples, only the first element of the array will be of type byte. Commented Oct 19, 2023 at 17:38
  • Data is 128 bits so I would make a string using Following : [string]::Join('', ($var1 | foreach { $_.ToString("X2")})) Commented Oct 19, 2023 at 17:46
  • 1
    switch ("$value") "$var1" {act1} "$var2" {act2} Commented Oct 19, 2023 at 18:15

1 Answer 1

3

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}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.