Home > Software design >  PowerShell Switch statement with array for condition
PowerShell Switch statement with array for condition

Time:08-04

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.

CodePudding user response:

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

CodePudding user response:

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

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

elitedesk2 matches
  • Related