Kelly Garcia
asked on
powershell switch statement
Hi All,
I have written the below switch statement however it does not work, please help:
I have written the below switch statement however it does not work, please help:
$a = "lp-lon-5673"
switch ($a) {
"lp-lon*" {"It is London Laptop."}
"lp-rom*" {"It is Romania Laptop."}
{($_ -eq "lp-sing*") -or ($_ -eq "LP-USA*")} {"It is a singapore or USA Laptop"}
4 {"It is four."}
}
ASKER
thanks for the code however this don't work:
$a = "LP-USA-12312"
switch -Wildcard ($a) {
"lp-lon*" {"It is London Laptop."}
"lp-rom*" {"It is Romania Laptop."}
{($_ -eq "lp-sing*") -or ($_ -eq "LP-USA*")} {"It is a singapore or USA Laptop"}
4 {"It is four."}
}
Same problem, this time with use of the -eq operator. Equality, not a wildcard comparison. Sorry, I didn't see that one first time around.
$a = "LP-USA-12312"
switch -Wildcard ($a) {
"lp-lon*" {"It is London Laptop."}
"lp-rom*" {"It is Romania Laptop."}
{($_ -like "lp-sing*") -or ($_ -like "LP-USA*")} {"It is a singapore or USA Laptop"}
4 {"It is four."}
}
eq becomes like which supports wildcards.
You might want to switch to regex here, more elegant:
$a = "LP-USA-12312"
switch -RegEx ($a) {
'lp-lon.*' {"It is London Laptop."}
'lp-rom.*' {"It is Romania Laptop."}
'lp-sing.*|lp-usa.*' {"It is a singapore or USA Laptop"}
4 {"It is four."}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
While this is already answered, I would encourage you to use break in your switch evaluations. If you do not, your script will continue to evaluate all switch statements. Its more efficient and it can avoid situations where there is potential to match more than 1 result.
Vs. breaking out of the switch loop.
Not really a big deal, but I always point it out when people aren't doing it.
switch ("Match me") {
"Match me" {"1st match"}
"Match me" {"2nd match"}
"Match me" {"woe is me it just keeps going"}
default {"unmatched"}
}
Vs. breaking out of the switch loop.
switch ("Match me") {
"Match me" {"1st match"; break}
"Match me" {"2nd match"; break}
"Match me" {"woe is me it just keeps going"; break}
default {"unmatched"}
}
Not really a big deal, but I always point it out when people aren't doing it.
ASKER
Thank you LearnCTX, very useful to know.
Switch has a wildcard parameter though.
Open in new window
It can also do regular expressions (RegEx) parameter if you need something more advanced.