Willy
Willy

Reputation: 10660

Renaming AD user object name in powershell

I am trying to get only AD Objects of type user and then iterate over all them and change AD user object name. So I have done below:

$Users = Get-ADObject -Filter {(ObjectClass -eq "user")} # OR Get-ADObject -Filter 'ObjectClass -eq "user"'

$Users | foreach
{
    # Here code to create name based on conditions ($newUserObjectName)
    Rename-ADObject -Identity $_ -NewName $newUserObjectName
}

The problem is that Get-ADObject is returning not only users but also computer objects.... I only want user object classes. Also I am not sure If below line of code is correct by setting identity to $_ in order to update the current user in the iteration:

Rename-ADObject -Identity $_ -NewName $newUserObjectName

Upvotes: 0

Views: 7573

Answers (3)

spicy.dll
spicy.dll

Reputation: 957

Use Get-ADUser and Set-ADUser:

$Users = Get-ADUser -Filter *
$Users | foreach {
    # Naming code
    Set-ADUser -Identity $_.SamAccountName -SamAccountName $newName
}

This replaces all user's identities to $newName.

Note you can replace -SamAccountName with any other property of an ADUser. for example if you want to replace the display name instead, you would use -Name $newName

Upvotes: 0

Sid
Sid

Reputation: 2676

The Computer objectClass is derived from the User objectClass. Hence, queries for user class will return both Computers and Users. If you want to filter for Users only, you have to specify ObjectCategory as Person

$Users = Get-ADObject -Filter {(Objectclass -eq "user") -and (objectCategory -eq "Person")}

Use that or you can use the goodole Get-ADuser

Upvotes: 2

Mark Harwood
Mark Harwood

Reputation: 2415

Why not use Get-ADUser instead of Get-ADObject and just return the DistinguishedName? Obviously, DON'T just run this code :)

$users = (Get-ADUser -Filter *).DistinguishedName #This gets all the users in AD
Foreach($user in $users){
    Rename-ADObject -Identity $user -NewName $newUserObjectName
}

Upvotes: 2

Related Questions