Powershell - SET-ADUSER Modify samaccountname

27,062

Assuming your first few lines are working to retrieve the correct results, this foreach block should work:

foreach ($user in $users) 
{
    $newSamAccoutname = $user.SamAccountName.replace("adm","tst")
    Set-ADUser $user -Replace @{samaccountname=$newSamAccoutname} 
}
Share:
27,062
Richard
Author by

Richard

Updated on July 09, 2022

Comments

  • Richard
    Richard almost 2 years

    New to powershell and still trying to get the logic.

    I would like to filter out the samaccountname's in active directory in a specific OU, that also contain "adm" at the end of the string (phil_test_adm). When the users are found i want to replace with the "adm" with "tst". So far i have the below, again i am struggerling with the logic.

    import-module activedirectory
    $Path = 'OU=Example, OU=Users,DC=uk,DC=random,DC=com'
    $users = Get-ADUser -filter 'SamAccountName -like "*adm"' -SearchBase $Path | select-object samaccountname, name
    #foreach ($user in $users) 
    #{
    #Set-ADUser $user.samaccountname -Replace { 
    #if $user.sammaccountname -eq "*adm"  }
    

    As you can see where foreach begins i have just been playing about. Thank you for any help!