Forum Discussion

Twrriglesworth's avatar
Twrriglesworth
Copper Contributor
May 03, 2024

Repeating a task

Hi all, 

 

We are currently using Power Automate to create on-prem users. The problem we've hit is that the UPN suffix is blank (different issue).

 

To get around this, I've made a PowerShell script that runs every 5 mins on a scheduled task. As I've found this evening, if there is more than one user that is missing a UPN suffix, it fails.

 

 

 

$LocalUsers = Get-ADUser -Filter {UserPrincipalName -notlike '*@*'} -Properties UserPrincipalName -ResultSetSize $null
$UPN = $LocalUsers.UserPrincipalName + "@tww-lab.co.uk"
Set-ADUser -Identity $LocalUsers.SamAccountName -UserPrincipalName $UPN

 

 

 

We want the script to find an entry missing a UPN suffix and correct it to Firstname.Lastname @ UPN

 

Is there a way we can do this or is there a better way to do this? 

  • Twrriglesworth If you get more than one user who needs changing, it stops because you don't loop through them. I changed the script and tested it in my environment, works 🙂 

     

    foreach ($user in Get-ADUser -Filter { UserPrincipalName -notlike '*@*' } -Properties UserPrincipalName -ResultSetSize $null) {
        $UPN = $User.UserPrincipalName + "@tww-lab.co.uk"
        try {
            Set-ADUser -Identity $User.SamAccountName -UserPrincipalName $UPN -ErrorAction Stop
            Write-Host ("Changed UPN of User {0} to {1}" -f $user.name, $upn) -ForegroundColor Green
        }
        catch {
            Write-Warning ("Error changing UPN of User {0} to {1}, check permissions! Skipping...")
        }
    }



    Please click Mark as Best Response & Like if my post helped you to solve your issue.
    This will help others to find the correct solution easily. It also closes the item.

    If one of the posts was helpful in other ways, please consider giving it a Like.

  • Twrriglesworth If you get more than one user who needs changing, it stops because you don't loop through them. I changed the script and tested it in my environment, works 🙂 

     

    foreach ($user in Get-ADUser -Filter { UserPrincipalName -notlike '*@*' } -Properties UserPrincipalName -ResultSetSize $null) {
        $UPN = $User.UserPrincipalName + "@tww-lab.co.uk"
        try {
            Set-ADUser -Identity $User.SamAccountName -UserPrincipalName $UPN -ErrorAction Stop
            Write-Host ("Changed UPN of User {0} to {1}" -f $user.name, $upn) -ForegroundColor Green
        }
        catch {
            Write-Warning ("Error changing UPN of User {0} to {1}, check permissions! Skipping...")
        }
    }



    Please click Mark as Best Response & Like if my post helped you to solve your issue.
    This will help others to find the correct solution easily. It also closes the item.

    If one of the posts was helpful in other ways, please consider giving it a Like.

Resources