Script repository
The script updates user accounts in Active Directory based on information from an SQL database. If a user does not have an account in Active Directory, the script will create it based on the information available in the database. Users are identified in AD by their Employee ID property value.
To use the script, install the Adaxes PowerShell module on the computer where the service runs.
To execute the script, create a scheduled task configured for the OrganizationalUnit object type.
Parameters
$databaseHost- the DNS host name of the computer where the SQL database is homed.$databaseName- the database name.$databaseUsername- the username of the account that will be used to connect to the database. If set to$nullthe credentials of the Adaxes service account (specified during the software installation) will be used.$databasePassword- the password that will be used to connect to the database.$propertyMap- Maps property names of user accounts with the corresponding database fields.$commandText- the SQL statement that will be issued to pull the necessary data from the database.
Import-Module Adaxes
$databaseHost = "host.company.com" # TODO: modify me
$databaseName = "MyDatabase" # TODO: modify me
$databaseUsername = $NULL # TODO: modify me
$databasePassword = $NULL # TODO: modify me
$propertyMap = @{
"employeeID" = "ID";
"name" = "Name";
"samaccountname" = "Username";
"givenName" = "FirstName";
"sn" = "LastName";
"displayName" = "DisplayName";
"description" = "Description";
"unicodePwd" = "Password";
"department" = "Department";
"company" = "Company";
"l" = "City";
"postOfficeBox" = "Office";
"AccountExpires" = "AccountExpiresDate";
} # TODO: modify me: $propertyMap = @{"LdapPropertyName" = "SQL database field"}
$commandText = "SELECT ID,Name,Username,FirstName,LastName,DisplayName,Description,Password,Department,Company,City,Office,AccountExpiresDate FROM UsersTable"
# TODO: modify me
# Connect to the database.
$connectionString = "Data Source=$databaseHost; Initial Catalog=$databaseName;"
if ($databaseUsername -eq $NULL)
{
$connectionString = $connectionString +
"Integrated Security=SSPI;"
}
else
{
$connectionString = $connectionString +
"User ID=$databaseUsername;Password=$databasePassword;"
}
try
{
$connection = New-Object "System.Data.SqlClient.SqlConnection" $connectionString
$connection.Open()
# Query user information from database.
$command = $connection.CreateCommand()
$command.CommandText = $commandText
# Load user information.
$reader = $command.ExecuteReader()
$usersFromDB = @{}
while ($reader.Read())
{
$valuesFromDB = @{}
foreach ($ldapPropertyName in $propertyMap.Keys)
{
$columnName = $propertyMap[$ldapPropertyName]
$value = $reader[$columnName]
# If the value is empty, skip it.
if ([System.String]::IsNullOrEmpty($value) -or ([System.Convert]::IsDBNull($value)))
{
continue
}
elseif ($value -is [System.String])
{
$value = $value.Trim()
}
elseif ($ldapPropertyName -ieq "accountExpires")
{
try
{
$value = $value.ToFileTime()
}
catch
{
continue
}
}
if ($value -ieq "True" -or $value -ieq "False")
{
$value = [System.Boolean]::Parse($property.Value)
}
$valuesFromDB.Add($ldapPropertyName, $value)
}
$usersFromDB.Add($valuesFromDB.employeeID, $valuesFromDB)
}
}
finally
{
# Close connection to the SQL database and release resources.
if ($reader) { $reader.Close() }
if ($command) { $command.Dispose() }
if ($connection) { $connection.Close() }
}
# Get domain name
$domainName = $Context.GetObjectDomain("%distinguishedName%")
foreach ($employeeId in $usersFromDB.Keys)
{
$userPropertiesFromDB = $usersFromDB[$employeeId]
# Get user password and remove it from the hashtable.
$userPassword = ConvertTo-SecureString -AsPlainText -String $userPropertiesFromDB["unicodePwd"] -Force
$userPropertiesFromDB.Remove("unicodePwd")
# Get other properties.
$propertiesToCheck = @($userPropertiesFromDB.Keys)
# Search user by Employee ID.
$user = Get-AdmUser -Filter {employeeId -eq $employeeId} -AdaxesService localhost -Server $domainName `
-Properties $propertiesToCheck -ErrorAction SilentlyContinue
if ($NULL -eq $user)
{
# The user account does not exist, create one.
# Get user identity, and remove it from the hashtable.
$name = $userPropertiesFromDB["name"]
$userPropertiesFromDB.Remove("name")
# Create user
try
{
$user = New-AdmUser -Name $name -OtherAttributes $userPropertiesFromDB -AdaxesService localhost `
-Server $domainName -Path "%distinguishedName%" -Enabled $True -ErrorAction Stop -PassThru
}
catch
{
$Context.LogMessage($_.Exception.Message, "Error")
continue
}
if ($userPassword -ne $NULL)
{
# Set password
Set-AdmAccountPassword -Identity $user.DistinguishedName -NewPassword $userPassword `
-Reset -Server $domainName -AdaxesService localhost
}
continue
}
# If the user exists, check whether any properties changed.
foreach ($propetyName in $propertiesToCheck)
{
# Remove properties with the same values from the hashtable.
if ($user."$propetyName" -ieq $userPropertiesFromDB[$propetyName])
{
$userPropertiesFromDB.Remove($propetyName)
}
}
if ($userPropertiesFromDB.Count -eq 0)
{
continue # Nothing changed
}
# Update user
Set-AdmUser $user.DistinguishedName -Replace $userPropertiesFromDB -AdaxesService localhost `
-Server $domainName
}
Comments 10
You must be signed in to comment.
Tim
How would the select statement ($commandText variable) look if I wanted to exclude a specific record based on value. For example, if I did not want to process any records where the Department was equal to "Facilities" with my import?
Support
Hello Tim,
In SQL, search conditions are specified in the WHERE clause. To exclude users whose Department property value equals Facilities from a selection, you should use a query like below in the $commandText variable:
Fachmi
1. How can I check if the account is exist or not with multiple value such as Employee ID, email, name?
If none of it found, then only create new user.
1. Can I get the data from Oracle table?
Support
Hello Fachmi,
>How can I check if the account is exist or not with multiple value such as Employee ID, email, name?
It will require significantly reworking the script as currently it only checks the Employee ID property.
>Can I get the data from Oracle table?
Yes, it should work just fine. The following article should be helpful:https://docs.microsoft.com/en-us/answers/questions/350779/query-oracle-database-using-powershell.html.
ngadimin
Hi, when i run this script on powershell ISE and Adaxes powershell module for AD, just showing this error message :
===================
You cannot call a method on a null-valued expression.
At C:\Users\ngadimin\importsqluser.ps1:107 char:1
+ $domainName = $Context.GetObjectDomain("%distinguishedName%")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
=============
Is there part that not correct?
Thanks.
Support
Hello,
The script is correct. However, it is using the predefined $Context variable. The script can only be executed in Adaxes custom commands, business rules and scheduled tasks. It will not work in Windows PowerShell. This behavior is by design.
user
why when I run the code above in Scheduled Tasks, the code above is not triggered, to run it must first press the run script button, is there a solution?
Support
Hello,
Scheduled tasks only run when the time you specify for them. Make sure that the schedule you specify meets your requirements. To change the schedule of an existing task, select it in Adaxes Administration console and click Change schedule on the right.
user
I've done that but it still doesn't trigger automatically, a message like this appears in the log
is there any solution ?
Support
Hello,
The provided messages mean that the scheduled task was modified and executed manually. For information on how to schedule tasks, have a look at the following tutorial: https://www.adaxes.com/tutorials_AutomatingDailyTasks_ScheduleTasksForActiveDirectoryManagement.htm. Should you still have issues running the task on a schedule, please, send us at support@adaxes.com a screenshot of the task configuration. Please, make sure to include the task schedule part in the screenshot.