we have a dozen people with popular names example Lee jones, theres also a Lou Jones.
So to create an email account we needed to use The 1st 2 initails in the first name for some user’s …pretty common place.
Any way to add some logic an If statement or a -like | -match operator that would identify a list of providied 1st names , where if its that 1st name like " Lee" then use 1st 2 initials for email address.
You could, depending on what database you’re looking at to verify the names. For instance, if you’re using Active Directory. I 'll have to pull in my buddy Stephen for some help on this as he’s a bit more of an AD guru than I. I’ll ping him.
Let’s start with the excellent code we have from Will so far, it isn’t too hard to check and see if a user exists with this name. If not, create mailbox, if so, try something different.
$data = Import-Csv 'C:\scripts\names.csv' -Header Names
ForEach[$Name in $data]{
$FName = $Name.Names
$First = $FName.substring[0,1]
$Last = $FName.Split[" "] | Select-Object -Last 1
$Email = $First + $Last + '@company.com'
if [[Get-ADUser $Email].Count -eq 0]{
#If no users exist with this e-mail addy
Enable-Mailbox $Email
}
ELSE{
#If there is a user with this address [we need to try another name]
$First = $FName.substring[0,2]
$Last = $FName.Split[" "] | Select-Object -Last 1
$Email = $First + $Last + '@company.com'
Enable-Mailbox $Email
}
}
This logic isn’t fully baked (for instance, what if you hired ten guys, named Steve Owen, Steven Owen, Stephen Owen, Stephanie Owen, etc!). If we wanted to procedurally catch for this, we can use this code below, allowing up to five letters in the user’s name.
$data = Import-Csv 'C:\scripts\names.csv' -Header Names
ForEach[$Name in $data]{
:countingLoop [1..5] | ForEach-Object {
$FName = $Name.Names
$First = $FName.substring[0,$_]
$Last = $FName.Split[" "] | Select-Object -Last 1
$Email = $First + $Last + '@company.com'
if [[Get-ADUser $Email].Count -eq 0]{
#If no users exist with this e-mail addy, make one and exit
Enable-Mailbox $Email
break countingloop
}
}
}
Thank you for the impressive solution you came up with.
I’m looking not so much to create/enable the email but more to retrieve the right email so i can use it with send-email cmdlet for a report I am doing . Thats why i need to be able to indicate a watch list of sorts to add the 2nd letter of the username