Search code examples
powershellactive-directoryldapwindows-server-2008-r2

Active Directory - Filling in unique ID by script


I want to fill in the "employeeID" or "uid" of our users in Active Directory with a sequential number. Only thing that I made is exporting the user in a CSV file:

Get-ADUser -Filter "mail -like '*com'" | Export-Csv 'C:\ADUser.csv' -NoType

Has anyone an idea how I can do anything like this?


Solution

  • This sets all the users EmployeeID fields to a number sequentially starting from 1:

    Get-ADUser -Filter "mail -like '*com'" | ForEach-Object -Begin {$UserID = 1} {
        Set-ADUser $_ -EmployeeID $UserID -WhatIf
        $UserID++
    }
    

    Remove the -WhatIf parameter if it looks to be doing what you desired. Beware that it will likely replace any existing value for all these users and it doesn't account for the possiblity that other user objects in the domain might have the same ID (as you've filtered to users with an email address).

    If you want a CSV output at the end with the results you could further do this:

    Get-ADUser -Filter "mail -like '*com'" | ForEach-Object -Begin {$UserID = 1} {
        Set-ADUser $_ -EmployeeID $UserID -WhatIf
        $UserID++
    
        Get-ADUser $_ -Properties Samaccountname,EmployeeID | Select Samaccountname,EmployeeID        
    } | Export-Csv 'C:\ADUser.csv' -NoType