Hello,
The following version of the script will do the job:
Import-Module Adaxes
$csvFilePath = "\\server\share\ImportedUsers.csv" # TODO: modify me
$userIdColumn = "DepartmentNumber" # TODO: modify me
$userIdProperty = "departmentNumber" # TODO: modify me
function UpdateDepartmentNumberInProperty($string, $pattern, $departmentNumber, $userObject, $propertyName, $userName)
{
$result = $string | Select-String -Pattern $pattern
if ($result -eq $NULL)
{
$Context.LogMessage("The department number was not found in the $propertyName '$string' for user '$userName'. ", "Warning")
return $NULL
}
$oldDeprtmentNumber = $result.Matches[0].Value
$string = $string.Replace($oldDeprtmentNumber, $departmentNumber)
$userObject.Add($propertyName, $string)
}
$domainName = $Context.GetObjectDomain("%distinguishedName%")
$importedUsers = Import-Csv -Path $csvFilePath
foreach ($userFromCSV in $importedUsers)
{
$userObject = @{}
foreach ($property in $userFromCSV.PSObject.Properties)
{
$columnName = $property.Name
$value = $property.Value
# Parse special columns
if ($columnName -ieq $userIdColumn)
{
$propertyName = $userIdProperty
}
else
{
$propertyName = $columnName
}
$userObject.Add($propertyName, $value)
}
# Build department
$department = [System.String]::Format("{0}, {1} - {2}", @($userObject["l"], $userObject["st"], $userObject.$userIdProperty)) # TODO: modify me
$userObject.Add("department", $department)
# Check whether the user exists
$valueForSearch = $userObject.$userIdProperty
$userExists = Get-AdmUser -LdapFilter "($userIdProperty=$valueForSearch)" `
-AdaxesService localhost -Server $domainName -Properties "displayName", "description"
if ($userExists -eq $NULL)
{
$Context.LogMessage("User with value '$valueForSearch' in property '$userIdProperty' does not exist", "Warning")
continue
}
if ($userExists -is [System.Array])
{
$Context.LogMessage("Found more than one user with value '$valueForSearch' in property '$userIdProperty'", "Warning")
continue
}
# Update Display name
UpdateDepartmentNumberInProperty $userExists.DisplayName "(?<=.+\s)[0-9]+(?=\s.+)" $userObject.$userIdProperty $userObject "displayName" $userExists.Name
# Update Description
UpdateDepartmentNumberInProperty $userExists.Description "(?<=.+\s)[0-9]+$" $userObject.$userIdProperty $userObject "description" $userExists.Name
# 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 '$($userExists.Name)'. Error: " + $_.Exception.Message, "Warning")
}
}