Set Active Directory user attributes automatically with PowerShell

Scenario:

Set Active Directory user attributes automatically with PowerShell.

During a check in Active Directory and on the details of the users I found out that a lot of information is wrong or missed. I was trying to perform some filtering and due to wrong information I was not able to. To solve my problem I wrote the below script that runs once per day and input the missing data or corrects the data according to what it was suppose to be, based on the Organizational Unit the the user belongs.

The script check and correct the data of the below attributes:

Company

Country

CustomAttribute1

Let’s see some details of the script to understand what actually is doing.

First of all the script is connected in Exchange server and imports the module of Active Directory. The reason I am connecting to exchange server is to set the custom attribute of the user. The custom attribute is actually an exchange attribute of a user mailbox. Then we are retrieving the information of our users and keep them in a variable. After that I set the values that I want to be based on the Organizational Unit of the user. Afterwords a check is performed for each user if it meets that values that I want the users to have. If the value is empty or something is missing the script changes the value to the correct one.

As I have mentioned before, custom attribute is an exchange attribute. So before any check on the attribute I have to check if the user is mail enabled. If you will not check if the user is mail enabled then the script will try to change custom attribute for all users, if through they do not have a mailbox and you will receive errors. As you will find in the script I am using two different ways of setting the custom attribute. This needs to be done if you have a Hybrid Environment for your Exchange. The users that are under Exchange On-Premise you have to use the set-mailuser command. For the users that they belong to Exchange Online (Office365), based on the Hybrid environment you have to set the change on Exchange On-Premise and the change will be synced to Office365. As you will see the set-remotemailbox command is used on Exchange On-Premise for the change of custom attribute on those users.

After all the changes are done, if there are any, a report will be sent to me let me know the user that the change was on and provide me the values that have been set for that user. If there will be any errors while the script is running, Another email will be send providing me those errors, so I will be able to check what went wrong and manually perform some actions to correct the errors.

You can download the script here or copy it from below.

Comment below for any questions you may have or anything else that you want.

Related Links:

Solution / Script: