Can't get 'switch' statement to work properly

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Tony Tony 1 year, 6 months ago.

  • Author
    Posts
  • #26996
    Profile photo of Tony
    Tony
    Participant

    I've got a messy Exchange 2007 powershell script I'm trying to clean up and convert to Exchange 2013. Among one of the messes is a long set of if/elseif commands I'm trying to move to 'switch'.

    —————————————————————————————————-
    $databasename=(Get-MailboxDatabase | foreach {Get-ChildItem ("\\" + $_.Server + "\" + $_.edbFilePath).Replace(":","$")| Where-Object{$_.Name -ne "Separated.edb" -and $_.Name -ne "Journal.edb"}} | sort -property length)[0].name.TrimEnd(".edb")

    switch($databasename.startswith){
    "MDB1" {$servername="SRV-EXCH1.company.com"}
    "MDB2" {$servername="SRV-EXCH2.company.com"}
    "MDB3" {$servername="SRV-EXCH3.company.com"}
    "MDB4" {$servername="SRV-EXCH4.company.com"}
    "MDB5" {$servername="SRV-EXCH5.company.com"}
    "MDB6" {$servername="SRV-EXCH6.company.com"}
    "MDB7" {$servername="SRV-EXCH7.company.com"}

    default {$servername="Something went wrong"}
    }

    —————————————————————————————————-

    But for some reason it doesn't work. I have to be missing something simple. What is it?

    [PS}>$databasename.startswith("MDB7")
    True

    [PS]>$databasename
    MDB703
    [PS]>$servername
    Invalid entry

  • #26997
    Profile photo of Tony
    Tony
    Participant

    Support question.

  • #26998
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    You can't use a method like that in your switch statement. However, the switch statement does support -Wildcard and -Regex options, both of which would work here:

    switch -Wildcard ($databasename) {
        "MDB1*" {$servername="SRV-EXCH1.company.com"}
        "MDB2*" {$servername="SRV-EXCH2.company.com"}
        "MDB3*" {$servername="SRV-EXCH3.company.com"}
        "MDB4*" {$servername="SRV-EXCH4.company.com"}
        "MDB5*" {$servername="SRV-EXCH5.company.com"}
        "MDB6*" {$servername="SRV-EXCH6.company.com"}
        "MDB7*" {$servername="SRV-EXCH7.company.com"}
    
        default {$servername="Something went wrong"}
    }
    
  • #26999
    Profile photo of Tony
    Tony
    Participant

    That did it. Thanks!

You must be logged in to reply to this topic.