Friday, September 14, 2012

Updating Active Directory User Attributes via PowerShell

One of the issues I have encountered is how to update an attribute for multiple user accounts when the attribute is not one of what Microsoft refers to as a "commonly used property value". For example, we use an attribute called "employeeType" to store an employee's Organization Code. This is not an attribute that you'd see if you select multiple accounts and view the Properties. So, how do you update the attribute? Well, in researching the issue, I came across this site, and I was able to use it as a springboard to get to a solution that fit my needs. The missing piece for me was that the Get- and Set- commands don't know what to do with the uncommon property value, but looking into the command usage via TechNet got me the rest of the way to a solution. As you will see with most of my scripts, I like to use a CSV file as my input for the scripts since it is common for me to update anywhere from a few to dozens (if not hundreds) of accounts at one time.


#################################
# Script to update attributes for Active Directory users
#
# Script by SLCSysAdmin - please credit and link!
# http://slcsysadmin.blogspot.com
#
# NOTE: be sure that "Active Directory Module for Windows PowerShell" 
# is loaded in PowerShell before running
#################################

$dataSource=import-csv "AccountList.csv"
foreach($dataRecord in $datasource) {
$sAMAccountName=$dataRecord.sAMAccountName

# List of attributes to update
$employeeType=$dataRecord.employeeType
$department=$dataRecord.department

# NOTE: For the following item, the extra code is necessary because "employeeType" is not 
# one of the "commonly used property values" as found in the following list:
# http://technet.microsoft.com/en-us/library/ee617215.aspx
Get-ADUser -Identity $sAMAccountName -Properties employeeType | Set-ADUser -Replace @{employeeType=$employeeType}

# NOTE: The following is much simpler because "department" is one of the common property values
Get-ADUser -Identity $sAMAccountName | Set-ADUser -Department $department
}

It is worth mentioning for first-timers that your column names in your CSV file need to match what you're doing in your script. For example, my CSV file would look like this for use with the code above:

sAMAccountName,employeeType,department
usernameA,1234,IS
usernameB,9876,BB
...
usernameZ,3476,ZZ

When the request comes in to update different attributes, make the necessary changes to the script and make sure you update your columns in your CSV file accordingly. Enjoy, and feel free to hit me with your comments or suggestions!

4 comments: