Home > Back-end >  How to replace an email domain using PowerShell
How to replace an email domain using PowerShell

Time:12-20

I'm inputting a $PrimaryOwner email like this and I'm just wondering how can I change the domain to be always China Tenant domain no matter what type of domain I'm passing.

For example:

input
[email protected]
[email protected]
[email protected]

output
[email protected]
[email protected]
[email protected]

I'm using replace() like this and it's working fine but this look very redundant so I'm just wondering if there is way to simplify it because I have like over 10 different domains for my $Primaryowner and $SecondaryOwner.

I thought there would be more simpler version because I'm outputting the same china domain so any suggestion or help would be really appreciated.

        if ($PrimaryOwner -like "*gmail*") { 
            $PrimaryOwner = $PrimaryOwner.replace("gmail.com", "china.com")
        }
        elseif ($PrimaryOwner -like "*yahoo*") {
            $PrimaryOwner = $PrimaryOwner.replace("yahoo.com", "china.com")
        }
        elseif ($PrimaryOwner -like "*ymail*") {
            $PrimaryOwner = $PrimaryOwner.replace("ymail.com", "china.com")
        }


CodePudding user response:

Use the MailAddress Class to parse your addresses:

$mails = @(
    '[email protected]'
    '[email protected]'
    '[email protected]'
)

foreach($mail in $mails) {
    '{0}@china.com' -f ($mail -as [mailaddress]).User
}
  • Related