Search code examples
powershellpowershell-4.0powershell-remotingpowershell-cmdlet

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?


Solution

  • 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