Copy UPN to SamAccountname

This topic contains 3 replies, has 2 voices, and was last updated by  Chris 1 year ago.

  • Author
  • #73423

    Jaapie bakker

    Hi Guys,

    I am look for an script which point at a specify OU and that it will adjust all the accounts that are in there but not any folders lower.

    I found out that i can do it for one user like this:

    $user = Get-ADUser -Identity "samaccountname"

    $newsam = ($user.userprincipalname -split "@")[0]

    $user | Set-ADUser -SamAccountName $newsam

    but now i have to fill in everytime the name of the user and we have like 1000 accounts. Could you please help me?

    Thanks in advanced.

  • #73439


    Hi Jaapie,

    I think the best way to do this would to be to use the -Searchbase functionality of Get-ADUser, narrow it down to the OU you want to target, assign to a variable, then use a foreach loop to make the changes you want,

    import-module ActiveDirectory
    $user = Get-ADUser -Filter * -SearchBase "OU=users,OU=students,DC=example,DC=internal"
    foreach ($user in $users) {
        "Code Here"

    This will eliminate the need to go through all 1000 users.

    • #73550

      Jaapie bakker

      Thanks for you reply Chris. After some testing i managed to get the job done, see script below:

      $ou = "OU=users,OU=students,DC=example,DC=internal"

      $server = "dc01"

      Get-ADUser -SearchBase $ou -Filter * | ForEach-Object {
      $newsam = ($_.userprincipalname -split "@")[0]
      $_ | Set-ADUser -SamAccountName $newsam }

  • #73556


    Hi Jaapie,

    Glad you got it working 😀

You must be logged in to reply to this topic.