PowerShell – Generate and email list of new users created in AD – Updated

If you don’t have an AD user provisioning tool implemented in your environment, I’m sure most of your user provisioning and de-provisioning is done using PowerShell scripts which helps in reducing the amount of time consumed in this process.

You probably are bombarded with requests from various departments in your organization to provide them with a list of new users who were created for various reasons.

This script can be automated by securely storing the credentials and running a scheduled task that runs on a specific day. Don’t store your admin or any credentials in any of your scripts.

You can use ConvertFrom-SecureString command to get an encrypted standard string and ConvertTo-SecureString to simply reverse the process by importing the data from your file and then create a PSCredential object.

(Get-Credential).Password | ConvertFrom-SecureString | Out-File "C:\Temp\Password.txt"

$User = "AdminUser@acme.com"
$File = "C:\Temp\Password.txt"
$MyCredential=New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, (Get-Content $File | ConvertTo-SecureString)

In this above method, the point of converting password to a SecureString and storing it in a file is to keep it out of plain text in PS scripts so that it’s not as easily discovered. This can be easily decrypted and not recommended.

You can use the Microsoft.PowerShell.SecretManagement and Microsoft.PowerShell.SecretStore PS modules which I’ve covered in a later post.

​$Days = -7
$Maxdate = (Get-Date).addDays($Days) 
$CurrentWeekNumber = Get-Date -UFormat %V

$dateformat = "dddd MM/dd/yyyy"
$subjDate = Get-Date $Maxdate -Format $dateformat

$NewUsers = Get-ADUser -filter { whencreated -ge $Maxdate} -Properties EmailAddress, co, Description | Select-Object -Property GivenName, SurName, DisplayName, Description, co, EmailAddress # Gathering recent New AD Users

if ($NewUsers) # If there are more than one new user created in last $Days, prepare to send a mail
    $MailBody = $NewUsers | ConvertTo-Html -Fragment
            $MailParams = @{Body       = $mailBody | Out-String
                            BodyAsHtml = $true
                            From       = "AD-Admin@acme.com"
                            To         = "jsmith@acme.com" # separate with comma for multiple users. "jdoe@acme.com", "jroe@acme.com"
                            SmtpServer = "smtp.acme.com"
                            Subject    = "New users for the week : $CurrentWeekNumber | Week Starting - $subjDate"
                            Encoding   = "UTF8"
                            Priority   = "Normal" # Accepted values: Normal, High, Low
                            #Port      = xxxx #If not 25
                            Credential = $(Get-Credential)
    Send-MailMessage @MailParams

Hope this script was useful is generating weekly reports of newly created AD users.

Thank you for stopping by. ✌

Leave a Comment