Ed R.
Ed R.

Reputation: 181

PowerShell Switch statement with array for condition

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.

Upvotes: 1

Views: 1345

Answers (2)

js2010
js2010

Reputation: 27491

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

Upvotes: 0

Keith Miller
Keith Miller

Reputation: 802

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
    }
}

Upvotes: 2

Related Questions