Let’s say you want to perform an ad-hoc test deployment. You build a small test collection and go to deploy, but wait – you ought to do your due diligence and notify the primary users of the targeted devices, right? You highlight primary user data in the console and attempt to copy it to a spreadsheet, but the resulting cells contain the domain name appended to the SAMAccountName – how convenient. /s
You could proceed to look up each user in Active Directory and build a spreadsheet, but that is tedious and cumbersome. Such toil ought to be eliminated when possible. And you’re in luck! I’ve already done the work. Specify your domain name in SAM format rather than UPN format (read more on that here: https://4sysops.com/archives/understand-the-upn-and-samaccountname-user-account-attributes/). Don’t worry about that pesky backslash, case-sensitivity, empty lines, or case-inconsistency in AD data– this script can handle all of these common deal-breakers. It will accept data copied straight from the Primary User column in the CM console and will output an easily-parsable .CSV containing names, usernames, and email addresses of the targeted individuals.
# Script written by Payton Flint
# See https://paytonflint.com/generate-email-list-from-cm-primary-user-data/
# Set domain name variable
$Domain = "<INSERT DOMAIN>"
# Set list file name
$FileName = "UserList.txt"
#Set output file name
$OutputFileName = "MailList.csv"
#===================================================================================================
# Append backslash character to domain name variable if not present
if ($Domain -NotLike "*\"){
$Domain += "\"
}
# Derive lowercase domain variable
$LCDomain = "$Domain".ToLower()
# Derive uppercase domain variable
$UCDomain = "$Domain".ToUpper()
# Identify location of script
$ScriptPath = Split-Path ($MyInvocation.MyCommand.Path) -Parent
# Get content from list, ignore blank lines
$ListContent = Get-Content "$ScriptPath\$FileName" | Where-Object {$_.Trim() -ne "" }
# Remove domain from list items
$Usernames = $ListContent | ForEach-Object {
$_.Replace("$LCDomain", "").Replace("$UCDomain", "")
}
# Run AD query on username list and write to array
$Output = ForEach ($Username in $Usernames) {
$User = Get-ADUser -filter "SamAccountName -eq '$Username'" -Properties DisplayName, EmailAddress
# Create array
[PSCustomObject]@{
Name = $User.DisplayName
Username = $User.SamAccountName
EmailAddress = $User.EmailAddress
}
}
# Write output to .CSV
$Output | Export-CSV -Path "$ScriptPath\$OutputFileName" -NoTypeInformation