meallhour
meallhour

Reputation: 15599

Replacing multiple if statements

I am using PS version 5.0 and I have quite a few if statements which might grow over time.

if ($hostname -like "**12*") {
    Write-Output "DC1"
} elseif ($Hostname -like "**23*") {
    Write-Output "DC2"
} elseif ($Hostname -like "**34*") {
    Write-Output "DC3"
} elseif ($Hostname -like "**45*") {
    Write-Output "DC4"
}

Can you suggest some better way of writing the same code?

Upvotes: 0

Views: 476

Answers (1)

BenH
BenH

Reputation: 10044

You could use a switch statement. Here is an example using the -Regex flag since it looks like you are doing just a simple match and then could cut out the * wildcards.

$hostname = 'asdf12asdf'
switch -Regex ($hostname) {
    "12" {Write-Output "DC1"}
    "23" {Write-Output "DC2"}
    "34" {Write-Output "DC3"}
    "45" {Write-Output "DC4"}
    Default {Write-Error "No Match Found"}
}

If you didn't want multiple matches add a ; Break after each case. For example if you had a host name such as asdf12asdf34 a statement "12" {Write-Output "DC1"; Break} would prevent the output both of 12 and 34

Upvotes: 3

Related Questions