Friday, November 15, 2013

PowerShell: Get a list of users who had Email Address don't complies with the company email address policy

In all organization there are a policy for almost everything, including the email address for the employees.
Each employee should have an email address with a specific format, like FirstName DOT LastName@Domain.com , or FirstLetter of FirstName DOT Lastname @Domain.com.
But sometime you find that there are some users dont complies with the policy, maybe a previous IT create them or miss type or miss configuration of your mail server, so you want to know these accounts.
In my Powershell script I will search for all users with email address dont match the following policy
Firstletter of Firstname DOT Lastname@Domain.com
so here we go
#clear the screen
cls
#Get a list and some details for all the users in my active directory
#I used the filter userAccountControl to get a list of the active /Enabled users account
#I dont want the result to include any disabled users
$alluserdetails=Get-ADUser -Properties Givenname,sn,sAmaccountname,mail,displayname,userAccountControl -Filter{userAccountControl -ne 514} | select Givenname,sn,sAmaccountname,mail,displayname,userAccountControl
foreach ($useraccount in $alluserdetails){
# What I will do is :
# - Read each user account and take the First Letter of his First name 
# - Add a DOT "."
# - Add the full last name + including the domain name
# Each user in my AD should have an Email address that match this policy
$surname=$useraccount.sn
$firstname=$useraccount.Givenname.get_Chars(0)
$newemailaddress=($firstname+"."+$surname+"@domain.com").ToLower()

# I will compare between the current Email address the user have with the one that complies with the policy
#if the $newemailaddress (the correct Email) do not equal $useraccount.mail (the one he had)
# Powershell will right the output
#its possible to change this Email, but first you need to know what Email service you are using and how to modify it by PS
if ($newemailaddress -notlike $useraccount.mail){
Write-Host $useraccount.displayname 
} 
}


Easy yes? , hope so.
if there is anything not clear, just comment, and if its all clear, simple like and share it
Thanks

No comments: