PowerShell: Creating a unique Alias / User Principal Name by querying existing recipient addresses

When creating a new user object via PowerShell in a large organisation,   it is important that we check for duplicate addresses before creating an account. The script below is an example of how we could do this.
 


$givenname = "Enter first name here"


$sn = "Enter last name here"


$Name = "$givenname.$sn"


$defaultname = $name




$Exit = 0


$Count = 1


Do


{


Try


{


# Checks for all email addresses which equals $name@domain.


$User =Get-Recipient "$name@enterdomain.com " -ErrorAction SilentlyContinue


If ($User -eq $null) {$Exit = 1}


else


{


# The user exists, add +1 to count


$Name = $defaultname + $Count++


}


}


Catch


{


# User does not exist. got to exit.


$Exit = 1








}


}


While ($Exit -eq 0)


$Alias = $name


$Alias # Returns available first.lastname which can be used for Alias and UserPrincipleName

Leave a Reply

Your email address will not be published. Required fields are marked *