Update AD Users' Email Address from CSV where this field is empty in AD (except specific domain)

Copper Contributor

Hi There,

 

I am trying to create a PS script with the following conditions and hoping someone here is able to guide me. Any assistance would be highly appreciated.

 

Import users from a CSV file with 2 fields (AcccountName, Email). The import process should target/update AD users matching the users in the CSV with "EmailAddress" AD Attribute when its blank (null) and exclude users who have an existing email address "@ourcompany.com" already within the AD Attribute. 

 

My script is as per below and it doesn't work. :(

 

Import-Module ActiveDirectory

$rootPath = "C:\Scripts"

$Users = Import-Csv -Delimiter "," -Path ($rootPath + "\Users.csv")

foreach($user in $Users){

 

IF
(Get-ADUser -SearchBase "CN=Users,DC=test,DC=local" -properties EmailAddress -Filter {EmailAddress -notlike '*mycompany.com' -and EmailAddress -eq ""})

 

{Set-ADUser -Identity $User.AccountName -EmailAddress $User.Email}

 

ELSE {Write-Host "No update possible as this User $user already has a Company Email Address"}
}

3 Replies

@PSNewie2021summat like:

foreach($user in $Users)
{
    $adUser = Get-ADUser -Identity $user.AccountName -Properties EmailAddress -ErrorAction SilentlyContinue
    if($adUser)
    {
        # user exists 
        if([System.string]::IsNullOrWhiteSpace($adUser.EmailAddress) )
        {
            # email address is empty, set it
            $adUser | Set-ADUser -EmailAddress $User.Email
        }
        elseif($adUser.EmailAddress -like '*mycompany.com')
        {
            # Leave this email alone. 
        }
        else
        {
            # email address exists, what to do here?  
        }
    }
    else
    {
        # The user does not exist.  This is probably an error of soem sort. 
    }
}

Assuming the Get-ADUser line succeeds  of course.

 

 

Good Day@psophos I like the idea of this, but I want to use it for something other then email.

Is this possible? IE, I need to modify the homePostalAddress, this is currently either clear or has a License code using A2B1 etc etc. I need the blanks to have this A2B1C1D1, the reason I cannot run a script to ovewright everything is everyone is not the same, some have A2B1C2D1J1 and some have A2B1C1D1J4 etc, 

@kevin_devon 

 

General etiquette would be to start your own thread for this question.

If you just want to set the field if its blank, then this is a two step process.
Not tested, but it will be something like.

 

Get-ADUser -properties homePostalAddress -filter 'homePostalAddress -notLike "*"' | 
  ForEach {Set-ADuser -Identity $_ -Add @{homePostalAddress = 'A2B1C1D1'}}