Script Repository


Import new and updated users from CSV file

June 14, 2019
2236

The script imports user accounts from a CSV file. Existing accounts are updated based on the data in the CSV file and non-existing ones are created in Active Directory. Existing users are identified by the property specified in the $userIdProperty variable.

Using the script, you can schedule users import from CSV files. For details, see Schedule Import of Users from a CSV File.

CSV File Sample:

sn,givenName,sAMAccountName,description,physicalDeliveryOfficeName,AccountPassword,manager
Robertson,William,wrobertson,Sales Manager at New York Office,New York,secret,Stephen Jones
John,Susan,sjohn,Senior Controller at LA Central,LA Central,,James Borwn
Smith,Elizabeth,esmith,---TERMINATED---,TERM,Z0eArjoQe

Parameters:

  • $csvFilePath - specifies a path to the CSV file that will be imported;
  • $userIdColumn - specifies the name of the column that contains the property for identifying existing users;
  • $userIdProperty - specifies the LDAP name of the property for identifying existing users (e.g. sAMAccountName, employeeID);
  • $accountPasswordColumn - specifies the name of the column that contains account passwords;
  • $customColumnNames - maps column headers with LDAP names of the corresponding user account properties. If mapping is not specified for a column header, the header specified in the file will be used as the property LDAP name;
  • $aDObjectProperties - specifies the list of headers of the columns that contain references to other AD objects, such as, Manager, Secretary or Assistant. Objects can be referenced in the columns by their:
    • Distinguished Name
    • Full name (cn attribute)
    • Display name
Edit Remove
PowerShell
Import-Module Adaxes

$csvFilePath = "\\SERVER\share\ImportUsers.csv" # TODO: modify me
$userIdColumn = "EmployeeName" # TODO: modify me
$userIdProperty = "sAMAccountName" # TODO: modify me
$accountPasswordColumn = "AccountPassword" # TODO: modify me
$customColumnNames = @{
    "JobTitle" = "title";
    "FirstName" = "givenName";
} # TODO: modify me
$aDObjectProperties = @("Manager", "Secretary") # TODO: modify me

$domainName = $Context.GetObjectDomain("%distinguishedName%")
$importedUsers  = Import-Csv -Path $csvFilePath

foreach ($userFromCSV in $importedUsers)
{
    $userObject = @{}
    $accountPassword = $NULL
    $propertiesToClear = @()
    foreach ($property in $userFromCSV.PSObject.Properties)
    {
        $columnName = $property.Name
        $value = $property.Value
        
        if ($columnName -ieq $accountPasswordColumn -and !([System.String]::IsNullOrEmpty($value)))
        {
            $accountPassword = ConvertTo-SecureString -AsPlainText $value -Force
            continue
        }
        elseif ($columnName -ieq $accountPasswordColumn -and [System.String]::IsNullOrEmpty($value))
        {
            continue
        }
        
        if ($customColumnNames.ContainsKey($columnName))
        {
            $propertyName = $customColumnNames[$columnName]
        }
        else
        {
            $propertyName = $columnName
        }
        
        if ([System.String]::IsNullOrEmpty($value))
        {
            $propertiesToClear += $propertyName
            continue
        }

        # Parse special columns
        if ($columnName -ieq $userIdColumn)
        {
            $propertyName = $userIdProperty
        }
        elseif ($aDObjectProperties -icontains $columnName)
        {
            $aDObject = Get-AdmObject -Filter {(Name -eq $value) -or (DisplayName -eq $value) -or (distinguishedName -eq $value)} `
                -AdaxesService localhost -ErrorAction SilentlyContinue -Server $domainName
            
            if ($aDObject -is [System.Array])
            {
                $Context.LogMessage("Found more than one object with identity '$value'.", "Warning")
                continue
            }

            if ($aDObject -eq $NULL)
            {
                $Context.LogMessage("Could not locate object with identity '$value'.", "Warning")
                continue
            }
            
            $value = $aDObject.DistinguishedName
        }

        if ($value -ieq "True" -or $value -ieq "False")
        {
            $value = [System.Boolean]::Parse($value)
        }

        $userObject.Add($propertyName, $value)
    }
    
    # Check whether the user exists
    $valueForSearch = $userObject.$userIdProperty
    $userExists = Get-AdmUser -LdapFilter "($userIdProperty=$valueForSearch)" `
        -AdaxesService localhost -ErrorAction SilentlyContinue -Server $domainName
    
    if ($userExists -eq $NULL)
    {
        # Build user name
        $displayName = $userObject.GivenName + " " + $userObject.SN
        $parameters = @{
            "Path" = "%distinguishedName%"
            "Name" = $displayName;
            "Server" = $domainName;
            "AdaxesService" = "localhost"
            "Enabled" = $True
            "OtherAttributes" = $userObject
            "ErrorAction" = "Stop"
        }
        
        if (!([System.String]::IsNullOrEmpty($accountPassword)))
        {
            $parameters.Add("AccountPassword", $accountPassword)
        }
        
        # Create a new user account
        try
        {
            New-AdmUser @parameters
        }
        catch
        {
            $Context.LogMessage("An error occurred when creating user '$displayName'. Error: " + $_.Exception.Message, "Warning")
        }
        continue
    }

    if ($userExists -is [System.Array])
    {
        $Context.LogMessage("Found more than one user with value '$valueForSearch' in property '$userIdProperty'", "Warning")
        continue
    }

    # If user exists, update account
    try
    {
        Set-AdmUser -Identity $userExists.DistinguishedName -Replace $userObject `
            -AdaxesService localhost -Server $domainName -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred when updating user '$displayName'. Error: " + $_.Exception.Message, "Warning")
    }
    
    if ($propertiesToClear.Length -ne 0)
    {
        try
        {
            Set-AdmUser -Identity $userExists.DistinguishedName -Clear $propertiesToClear `
                -AdaxesService localhost -Server $domainName -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when updating user '$displayName'. Error: " + $_.Exception.Message, "Warning")
        }
    }
    
    if ([System.String]::IsNullOrEmpty($accountPassword))
    {
        continue
    }
    
    try
    {
        Set-AdmAccountPassword -Identity $userExists.DistinguishedName -NewPassword $accountPassword `
            -Reset -Server $domainName -AdaxesService localhost -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred when updating the password for user '$displayName'. Error: " + $_.Exception.Message, "Warning")
    }
}

Comments ( 0 )
No results found.
Leave a comment