Author Posts

July 1, 2015 at 7:54 am

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

July 1, 2015 at 7:56 am

Support question.

July 1, 2015 at 8:09 am

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

July 1, 2015 at 8:16 am

That did it. Thanks!