Avatar of Basssque
Basssque
 asked on

Globally applying an Active Directory attribute using a PowerShell script

I can use the script below to apply an email address to a list of accounts using a csv list.  Can anyone help me change this script so it applies the matching username associated with each active directory account @domain.com  (smithj@domain.com) to all active directory accounts where the attribute is currently null?  Thanks!

Import-Csv -path C:\test.csv | ForEach-Object { $user = $_.sAMAccountName
	
	$department = $_.mail
	
	Get-Aduser -filter { sAMAccountName -eq $user } | set-ADuser -department $mail

Open in new window

Active DirectoryPowershell

Avatar of undefined
Last Comment
Jason Crawford

8/22/2022 - Mon
Jason Crawford

I don't think I understand the requirements but this is what I got so far:

foreach ($user in (Get-ADUser -Filter {Department -eq $null})) {
  Set-ADUser $user.samaccountname -Department $($user.mail)
}

Open in new window

Should the Department attribute for each AD user match their email address?
Chris Dent

Just about the same as Jason, plus the is empty check for the department attribute.
Import-Csv -path C:\test.csv | ForEach-Object {
    $department = $_.mail

    $adUser = Get-ADUser -Identity $_.SamAccountName -Properties department
    if (-not $adUser.Department) {
        $adUser | Set-ADUser -Department $department
    }
}

Open in new window

Basssque

ASKER
It wouldn't match their smtp address, no
Basically, if the domain I want to use is domain.com and the username of a user is smithj.  THen it should write smithj@domain.com to the mail attribute
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Basssque

ASKER
Chris,

I want to eliminate the need for the csv file and only apply this to all/any accounts in the entire Active Directory where the mail attribute is null.  I'm not sure I need department, I'm not sure why that was originally used.
ASKER CERTIFIED SOLUTION
Jason Crawford

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Jason Crawford

The script above will look for all AD users with an empty mail attribute.  For each of those users the mail attribute will be populated by concatenating the user's sAMAccountName with the "@domain.com" string.  Is that right?
Jason Crawford

Glad I could help.  Take care :)
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.