I have created a powershell script to connects to exchange online. The way it works is that, the script accepts a commandline argument as input(userprincipalname of a user), retrieves all mailboxes in exchange online then it checks if the user issued userprincipalname matches mailbox in exchange online. If the mailbox does not exist, i'm writing host, "mailbox does not exist", if the mailbox exists, i'm writing host "mailbox exists."
Problem The problem is the scripts returns both if and else statement bodies. I expect to see if statement body returned only if the mailbox exists and else statement body returned only if the mailbox does not exist.
What I'm i doing wrong.
Below is the script.
param($m)
# Add your Global admin plain password here
$password_ = "mysecurepassword"
$password = ConvertTo-SecureString $password_ -AsPlainText -Force
# Add your global administrator login email here.
$upn = "bernardmwanza@bernardcomms.onmicrosoft.com"
# Automated login to azure ad
$AppCredential = New-Object System.Management.Automation.PSCredential($upn, $password)
Connect-ExchangeOnline -Credential $AppCredential
# Retrieving all mailboxes in exchange online
$usermbxs = (Get-EXOMailbox).UserPrincipalName
foreach($usermbx in $usermbxs){
# Check if the user given mailbox exists in exchangeonline
if($m -match $usermbx){
write-host $m "Mailbox does exists"
}else{
write-host "The mailbox does not exist"
}
}
The output i get when i pass upn of a user who has mailbox in exchange online
The output i get when i pass upn of a user who does not exist in exchange online