0

PowerShell: Enabling AD users based on Employee Number

Consider the way people are hired, for a month, for a year or any other contract. As soon as it ended, most of the times the Active Directory user account will not be deleted immediately, but will be disabled. When using Auto creation tasks for new Active Directory users, for example with RES ONE Automation, it will create a new User Logon Account again, which might not be needed as the old one still exists.

Assumptions:

  • The Employee Number did not change.
  • The employeeNumber field of the Active Directory user is not empty because it was filled by an external data source (e.g. SQL, that has defined what tables have to be filled and can’t be NULL).
  • In this case, the Job Role and any applying groups will be the same.

The following script was created to check if there’s a Active Directory account with a given Active Directory EmployeeNumber, if not the field may be empty or the user has to be created. As the field in this case was filled automatically using RES ONE Service Store Setup and Sync Tool, which had a data connection to a SQL data source, this field could not have been empty in any way.

I used this script in a RES ONE Automation task to set a Parameter with Yes or No which would execute many other tasks to be executed.

Based on the outcome of this script, a former disabled user, with the same job role(s) and any applying Active Directory Groups will be enabled again.

To test this script start a Windows PowerShell (ISE) session, copy and paste into a text editor and save as a ps1 file, create an Active Directory user account with an EmployeeNr field filled as shown in the picture below and disable the Active Directory account and see if it will be enabled.


 

 

 

 

 

 

 

 

Import-Module ActiveDirectory

$EmployeeNumber = “1111” #Set variable with the EmployeeNumber. Within RES ONE Automation, as a parameter like “$[EmployeeNumber]”
$Empl = get-ADUser -Filter {EmployeeNumber -eq $EmployeeNumber} #Get to AD and show me the details of the user with EmployeeNumber
$EmpName = $Empl.SamAccountName #Set variable with the SamAccountName of the user that holds the EmployeeNumber
$CreateUser = “No”  #Set variable to ‘No’

if ($Empl -gt $Null){#Check if the EmployeeNumber is not empty, in other words, if it has value
if (!$Empl.Enabled) #If not enabled, then enable the account
 {Enable-ADAccount -Identity $EmpName
$CreateUser = “No” #Set the CreateUser parameter to ‘No’
}
}
elseif ($Empl -eq $Null){ #If EmployeeNumber can not be found based on an empty value, then consider the user to be non-existing and to be created
$CreateUser = “Yes” #Set the CreateUser variable to ‘Yes’ 
}
$CreateUser #Show the variable’s output

Leave a Reply

Your email address will not be published. Required fields are marked *