1

I'm trying to find a way to use an array of items, with wildcards, as a condition in a switch statement, and not having much success. Here's an example of what I'm trying to do,

$pcModel = "HP ProDesk 800 G5"
switch -Wildcard ($pcModel.ToUPPER()) {
    "*PROBOOK*" {  
        #Do something
        Break
    }
    "*ELITEBOOK*" {  
        #Do something else
        Break
    }

    {$_ -in "*ELITEDESK*", "*PRODESK*", "*ELITEONE*" }{
    # have also tried
    #{$_ -eq "*ELITEDESK*", "*PRODESK*", "*ELITEONE*" }
    #{"*ELITEDESK*", "*PRODESK*", "*ELITEONE*" -eq $_ }
    #{"*ELITEDESK*", "*PRODESK*", "*ELITEONE*" -like $_ }
    #{@("*ELITEDESK*", "*PRODESK*", "*ELITEONE*") -contains $_ }
        # Do other things
        Break
    }
    Default{
        # do nothing
        Break
    }
}

As I've commented in the code, I've tried numerous incarnations of an array with wildcards as a condition with no success. The condition always fails What am I missing. Before anyone chastises me for using ToUPPER because the switch statement is case insensitive, in this specific example I've found that to be false.

3
  • 1
    Instead of -wildcard, use -regex. A regular expression allows you to construct "A or B" type matches using the |: 'ELITEDESK|PRODESK|ELITEONE'. Commented Aug 3, 2022 at 23:12
  • WOW!!! thanks for that. I've always struggled with regex so I never consider it on my own but that was really easy. If you want to change your comment to an answer I'll mark it as accepted. Commented Aug 3, 2022 at 23:27
  • Will do...give me a few..... Commented Aug 3, 2022 at 23:29

2 Answers 2

2

Instead of the -wildcard option, use -regex. Regular expressions allow you to construct "A or B" type matches using the | OR operand:

$pcModel = "HP ProDesk 800 G5"
switch -regex ($pcModel.ToUPPER()) {
    'PROBOOK' {  
        #Do something
        Break
    }
    'ELITEBOOK' {  
        #Do something else
        Break
    }

    'ELITEDESK|PRODESK|ELITEONE' {
        # Do other things
        Break
    }
    Default{
        # do nothing
        Break
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

A more off the wall answer. Success if one of the 3 like's is true.

switch ('elitedesk2','elotedesk') {  
  { $true -in $(foreach ($pattern in "*elitedesk*","*prodesk*","*eliteone*") 
    { $_ -like $pattern }) } { "$_ matches" }
  default { "$_ doesn't match"}
}

elitedesk2 matches
elotedesk doesn't match

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.