turbonerd
turbonerd

Reputation: 1306

PowerShell script to update users' "Description" field with username as unique identifier

I have a CSV file containing just two columns - username and description.

I would like to update users' Description field in AD if their username is in this CSV.

The pseudocode for this would be something like:

foreach( Row in CSV ) {
    if( Row[username] exists in AD ) {
        ThisADAccount[Description] = Row[description]
    }
}

But frankly I have no idea how to do that in PowerShell!

In addition, at the same time, I would like to update these users' E-mail fields by setting [email protected]. The pseudocode for this would be:

foreach( User in AD ) {
    ThisADAccount[E-mail] = ThisADACcount[Username] + "@domain.com"
}

This only needs to be done if the account's username is in the CSV file however so the expanded pseudocode to achieve both of these jobs in one fell swoop would be:

foreach( Row in CSV ) {
    if( Row[username] exists in AD ) {
        ThisADAccount[Description] = Row[description]
        ThisADAccount[E-mail] = ThisADACcount[Username] + "@domain.com"
    }
}

If someone could help me to convert this pseudo into working PowerShell, it would be much appreciated.

Upvotes: 1

Views: 6292

Answers (1)

Richard
Richard

Reputation: 7000

First you will need to import the ActiveDirectory module to be able to edit objects in AD via PowerShell. Next you use Import-CSV, note you will need to change the -path and -Delimiter parameters to suit your CSV. I have also presumed that your CSV column headers are (username,Description).

Import-Module ActiveDirectory
$CSV = Import-Csv -Path 'T:\YourCSV.csv' -Delimiter ','

foreach( $Row in $CSV ) {
    if(Get-ADUser -LDAPFilter "(sAMAccountName=$($Row.username))") {
        Set-ADUser -Identity $Row.username `
                   -Description $Row.Description `
                   -EmailAddress "$($Row.username)@domain.com"
    }
}

You pretty much had the loop in the correct format for PowerShell you just need to use the cmdlets Set-ADUser to set the user properties and Get-ADUser to check if the AD user object exists.

Upvotes: 2

Related Questions