Jared Deckard
Jared Deckard

Reputation: 661

Change user mail property with ADSI in PowerShell

I am trying to update the email address of a directory user with PowerShell.

I am unable to modify the mail property of a user entry with the following code:

$BadUser = [adsi] $Account.Path

$BadUser.mail.Clear()
$BadUser.mail.Add($User.Email) | Out-Null

$BadUser.SetInfo()

The mail.Clear() nor the mail.Add() seem to modify $BadUser when debugging with PowerGUI.

I have a working version that relies on the QAD plugin, and I would like to avoid using it if possible.

$suf = $AD.Parent.Substring(10)

Connect-QADService -Service "$($AD.dc[0]).$suf" -ErrorVariable AD_Conn_Error -ErrorAction Stop -WarningAction Stop | Out-Null

Set-QADObject $Account.Properties.distinguishedname[0] -ObjectAttributes @{mail=$User.Email} | Out-Null

Disconnect-QADService

Reasons I am avoiding QAD:

Upvotes: 1

Views: 5934

Answers (1)

Elijah W. Gagne
Elijah W. Gagne

Reputation: 2841

Here's some example code to do it:

$query= "(&(objectCategory=User)(cn=FirstName LastName))"
$OU = "LDAP://OU=Users,dc=subdomain,dc=company,dc=com"
$PageSize = 100
$objOU = New-Object System.DirectoryServices.DirectoryEntry($OU)
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objOU
$objSearcher.PageSize = $PageSize 
$objSearcher.Filter = $query
$objSearcher.SearchScope = "Subtree"
$colResults = $objSearcher.FindAll()
foreach($objResult in $colResults) {
    $dirObject = [ADSI]$objResult.GetDirectoryEntry()
    $dirObject.mail = "[email protected]"
    $dirObject.CommitChanges()
}

Upvotes: 1

Related Questions