PowerShell : Data Normalisation

Well, this is something that occurs far to often than it needs to, you are ask to add people a group or perform a technology function with a list of people and you will get the following formats:
  1. List containing Firstname Surname (like Lee Croucher)
  2. List containing the Login ID (like LCrouc8 or LCroucher4)
Neither of these lists are very helpful when using Entra to add people to groups as for that you need the UPN, which usually follows the format of Firstnme.Surname@companydomain.com so this for a real example could be cheif.bear@pokebearswithsticks.com

Therefore the options you get the data in are not very help, so lets use PowerShell to fix this problem.

1. Firstname Surname List

If you get given a list of usernames in the Firstname Surname format then you can use this script to convert this into the UPN, ensure you update the file path with the location of your file with the usernames listed, this is the example input:


This is the script:

# Set the path to your text file
$filePath = "<path to txt file>"

# Read the text file line by line
$names = Get-Content $filePath

# Initialize an array to store formatted output
$output = @()

# Loop through each line in the text file
foreach ($name in $names) {
    # Split the line into first name and surname
    $firstName, $surname = $name -split ' '

    # Query Active Directory for the UPN using the first name and surname
    $user = Get-AdUser -Filter {GivenName -eq $firstName -and Surname -eq $surname} -SearchBase "OU=Users,DC=bear,DC=local"

    # Check if a user was found
    if ($user) {
        $upn = $user.UserPrincipalName
        $formattedOutput = "Input Name: $name --> UPN: $upn"
        $output += $formattedOutput
    } else {
        # If user not found, add an error message or handle it as needed
        $output += "User not found for Input Name: $name"
    }
}

# Output the results
$output

2. Login ID's

If you get given a list of login ID's, this is also known as the Pre-Windows 2000 login ID,  then you can use this script to convert this into the UPN, ensure you update the file path with the location of your file with the usernames listed, this is the example input:



This is the script:

# Import the Active Directory module
Import-Module ActiveDirectory

# Specify the path to your text file with login IDs
$loginIDsFile = "<path to TXT file> "

# Read the login IDs from the file
$loginIDs = Get-Content $loginIDsFile

# Loop through the login IDs and retrieve their UPNs
foreach ($loginID in $loginIDs) {
    $user = Get-ADUser -Filter {SamAccountName -eq $loginID}
    if ($user) {
        $UPN = $user.UserPrincipalName
        Write-Host "Login ID: $loginID --> UPN: $UPN"
    } else {
        Write-Host "Login ID: $loginID not found in Active Directory."
    }
}

This is the output:



Previous Post Next Post

نموذج الاتصال