0 votes

Hi Support,

We are looking to add a few things to one of the username creation scripts

If the upn/username is not unique, add a character of the first name to the last name until there are no more charters to add.
John Doe (Jdoe , Jodoe, JohDoe, JohnDoe)

If the upn/username is still not unique add a digit.
JohnDoe1

If someone with the same name already exists add the department field (IT) to the display name
Doe, John (IT)

If the Employee type has a value of c than the display name should be
Doe, John (Consultant)

If they have the employee type of i
Doe, John (Intern)

If they have an employee type of C or i and name already exists add the department (IT)
Doe, John (IT Intern)

  Import-Module Adaxes
    $upnSuffix = "xxxxx" # TODO: modify me

    #Check if UPN exists
    function IsUPNUnique($userLogonName)
    {
        if ($userLogonName -eq $NULL)
        {
             return $False
        }

        # Search users in all managed domain with specific UPN
        $searcher = New-Object "Softerra.Adaxes.Adsi.Search.DirectorySearcher" $NULL, $False
        $searcher.SearchParameters.PageSize = 500
        $searcher.SearchParameters.SearchScope = "ADS_SCOPE_SUBTREE"
        $searcher.SearchParameters.Filter = "(&(objectCategory=user)(userPrincipalName=$userLogonName))"
        $searcher.VirtualRoot = $True

        $result = $searcher.ExecuteSearch()
        $users = $result.FetchAll()
        $result.Dispose()

        if ($users.Count -eq 0)
        {
            return $True
        }

        return $False
    }

    function IsUPNUnique2($userLogonName)
    {
        if ($userLogonName -eq $NULL)
        {
             return $False
        }

        # Search users in all managed domain with specific UPN
        $searcher = New-Object "Softerra.Adaxes.Adsi.Search.DirectorySearcher" $NULL, $False
        $searcher.SearchParameters.PageSize = 500
        $searcher.SearchParameters.SearchScope = "ADS_SCOPE_SUBTREE"
        $searcher.SearchParameters.Filter = "(&(objectCategory=user)(userPrincipalName=$userLogonName))"
        $searcher.VirtualRoot = $True

        $result = $searcher.ExecuteSearch()
        $users = $result.FetchAll()
        $result.Dispose()

        if ($users.Count -eq 0)
        {
            return $false
        }

        return $true
    }

    function IsPropertyNameUnique($objectName, $domainName)
    {
        $user = Get-AdmUser -Filter {name -eq $objectName} -erroraction silentlycontinue -AdaxesService "localhost" -Server $domainName
        return $user -eq $Null
    }

    function IsUserNameUnique($username, $domainName)
    {
       $user = Get-AdmUser $username -erroraction silentlycontinue -AdaxesService localhost -Server $domainName
       return $user -eq $Null
    }

    # Get the user name info
    $username = $Context.GetModifiedPropertyValue("samAccountName")
    $userLogonName = $Context.GetModifiedPropertyValue("userPrincipalName")
    $sn = $Context.GetModifiedPropertyValue("sn")
    $givenName = $Context.GetModifiedPropertyValue("givenName")
    $domainName = $Context.GetObjectDomain("%distinguishedName%")

    # Check if the username is unique
    if (!(IsUPNUnique $userLogonName))
    {
        # Add Initials and check for uniqueness
        $initals = $Context.GetModifiedPropertyValue("initials")
        if ($initals -ne $NULL)
        {
            $uniqueUserLogonName = "%firstname:lower,1%%lastname:lower%@$upnSuffix"
            $uniqueUsername = "%firstname:lower,1%%lastname:lower%"

        }

        # If the username is not unique, generate a unique one
        for ($i = 2; $True; $i++)
        {
            if (IsUPNUnique $uniqueUserLogonName)
            {
                break
            }

            $uniqueUsername = $username + $i
            # Build new UPN
            $uniqueUserLogonName = "%firstname:lower,1%%lastname:lower%$i@$upnSuffix"
        }

        # Check sAMAccountName
        if (!(IsUserNameUnique $uniqueUsername $domainName))
        {
            $Context.Cancel("The username (SAMAccountName property) is not unique.")
            return
        }

        # Update User Logon Name (pre-Windows 2000)
        $Context.SetModifiedPropertyValue("samAccountName", $uniqueUsername)
        $Context.LogMessage("The username has been changed to " + $uniqueUsername `
          + ".", "Information")

        # Update User Logon Name
        $Context.SetModifiedPropertyValue("userPrincipalName", $uniqueUserLogonName)
        $Context.LogMessage("The UPN has been changed to " + $uniqueUserLogonName `
          + ".", "Information")
    }

    # Get the object DN
    $objectDN = $Context.TargetObject.ObjectInfo.DN;
    $objectLeaf = $objectDN.Leaf
    if (!(IsPropertyNameUnique $objectLeaf.Value $domainName))
    {
        for ($i = 1; $True; $i++)
        {
            $objectName = $objectLeaf.Value + " " + "(" + "%department%" + ")"
            if (IsPropertyNameUnique $objectName $domainName)
            {
                break
            }
        }

        # Rename the object
        $Context.SetModifiedPropertyValue("name", $objectName)
        $Context.LogMessage("The name has been changed to " + $objectName `
          + ".", "Information")
    }
by (50 points)

1 Answer

0 votes
by (216k points)
selected by
Best answer

Hello,

See a script that meets your requirements attached below. By the way, we made the script based on the following function from our Script Repository: BuildUsername. Give it a look. It is very easy to use. If necessary, you will be able to implement any changes in the future without our assistance.

The Script:

$upnSuffix = "domain.com" # TODO: modify me

function BuildUsername()
{
    $samAccountNameBuilder = New-Object "System.Text.StringBuilder"
    for ($i=0; $i -lt $args.length; $i++)
    {
        if (-not($args[$i] -is [array]))
        {
            if (-not([System.String]::IsNullOrEmpty($args[$i])))
            {
                [void]$samAccountNameBuilder.Append($args[$i].ToLower())
            }
        }
        elseif ($args[$i].length -eq 3)
        {
            if (-not([System.String]::IsNullOrEmpty($args[$i][0])))
            {
                switch ($Args[$i][2])
                {
                    "Beginning"
                    {
                        $value = $args[$i][0].SubString(0,$args[$i][1]).ToLower()
                    }
                    "End"
                    {
                        $value = $args[$i][0].SubString($args[$i][0].Length - $args[$i][1]).ToLower()
                    }
                }
                [void]$samAccountNameBuilder.Append($value)
            }
        }
        else
        {
            $Context.LogMessage("An error occurred while building a username!", "Error")
        }
    }

    return $samAccountNameBuilder.ToString()
}

Import-Module Adaxes

function IsUserPropertyUnique($propertyName, $value)
{
    # Search users in all managed domains
    $searcher = $Context.BindToObject("Adaxes://RootDSE")
    $searcher.PageSize = 500
    $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
    $searcher.SearchFilter = "(&(sAMAccountType=805306368)($propertyName=$value))"
    $searcher.VirtualRoot = $True

    try
    {
        $searchResultIterator = $searcher.ExecuteSearch()
        $searchResults = $searchResultIterator.FetchAll()

        return $searchResults.Length -eq 0
    }
    finally
    {
        if ($searchResultIterator) { $searchResultIterator.Dispose() }
    }
}

function SetProperty($propertyName, $value)
{
    $Context.SetModifiedPropertyValue($propertyName, $value)

    # Inform the user
    $Context.LogMessage("Property '$propertyName' was changed to $value", "Information")
}

# Get User Logon Name
$userLogonName = $Context.GetModifiedPropertyValue("userPrincipalName")
$sn = $Context.GetModifiedPropertyValue("sn")
$givenName = $Context.GetModifiedPropertyValue("givenName")

# Check whether User Logon Name is unique
$uniqueSamAccountName = $NULL
$uniqueUserLogonName = $NULL

if (-not (IsUserPropertyUnique "userPrincipalName" $userLogonName))
{
    # If User Logon Name is not unique, generate a unique one
    if ([System.String]::IsNullOrEmpty($sn) -or [System.String]::IsNullOrEmpty($givenName))
    {
        $Context.Cancel("First name and Last name must be specified for generating unique User Logon Name.")
        return
    }
    else
    {
        # Unique User Logon Name strategy 1:
        # Add characters from the first name until there are no more charters to add
        for ($i = 1; $i -le $givenName.Length; $i++)
        {
            $uniqueSamAccountName = BuildUsername @($givenName, $i, "Beginning") $sn
            $uniqueUserLogonName = "$uniqueSamAccountName@$upnSuffix"

            # Check whether User Logon Name is unique
            if (IsUserPropertyUnique "userPrincipalName" $uniqueUserLogonName)
            {
                break
            }

            $uniqueSamAccountName = $NULL
            $uniqueUserLogonName = $NULL
        }

        # Unique User Logon Name strategy 2: Add digits
        if ($uniqueUserLogonName -eq $NULL)
        {
            for ($i = 1; $True; $i++)
            {
                $uniqueSamAccountName = BuildUsername $givenName $sn "$i"
                $uniqueUserLogonName = "$uniqueSamAccountName@$upnSuffix"

                if (IsUserPropertyUnique "userPrincipalName" $uniqueUserLogonName)
                {
                    break
                }

            }
        }
    }
}

$name = $Context.GetModifiedPropertyValue("name")
$department = $Context.GetModifiedPropertyValue("department")
$employeeType = $Context.GetModifiedPropertyValue("employeeType")
$uniqueName = $NULL

if (-not (IsUserPropertyUnique "name" $name))
{
    # If Full Name is not unique, generate a unique one
    if ([System.String]::IsNullOrEmpty($sn) -or
        [System.String]::IsNullOrEmpty($givenName))
    {
        $Context.Cancel("First name and Last name must be specified for generating unique full name.")
        return
    }

    if (-not [System.String]::IsNullOrEmpty($department))
    {
        # Unique Full Name strategy 1: Use Department
        $uniqueName = "$givenName, $sn ($department)"
        if (-not (IsUserPropertyUnique "name" $uniqueName))
        {
            $uniqueName = $NULL
        }
    }

    if (-not [System.String]::IsNullOrEmpty($employeeType) -and $uniqueName -eq $NULL)
    {
        # Unique Full Name strategy 2: Use Employee Type
        switch ($employeeType)
        {
            "c"
            {
                $employeeTypeString = "Consultant"
            }
            "i"
            {
                $employeeTypeString = "Intern"
            }
            default
            {
                $employeeTypeString = $NULL
            }
        }

        $uniqueName = "$givenName, $sn ($employeeTypeString)"
        if ([System.String]::IsNullOrEmpty($employeeTypeString) -or -not (IsUserPropertyUnique "name" $uniqueName))
        {
            $uniqueName = $NULL
        }
    }

    if (-not [System.String]::IsNullOrEmpty($employeeTypeString) -and
        -not [System.String]::IsNullOrEmpty($department) -and
        $uniqueName -eq $NULL)
    {
        # Unique Full Name strategy 3. Using Department and Employee type
        $uniqueName = "$givenName, $sn ($department $employeeTypeString)"
        if (-not (IsUserPropertyUnique "name" $uniqueName))
        {
            $uniqueName = $NULL
        }
    }

    if ($uniqueName -eq $NULL)
    {
        # Failed to generate a unique full name. Cancel creation of the new user
        $Context.Cancel("A user with the same Full Name exists. Failed to generate a unique Full Name automatically. Input a unique Full Name manually.")
        return
    }
}

if (-not [System.String]::IsNullOrEmpty($uniqueUserLogonName))
{
    SetProperty "sAMAccountName" $uniqueSamAccountName
    SetProperty "userPrincipalName" $uniqueUserLogonName
}

if (-not [System.String]::IsNullOrEmpty($uniqueName))
{
    SetProperty "name" $uniqueName
}
0

Great. Thanks!!

0

Hi Support,

We are getting the following error when the script runs. If the user does not exist the script runs but throws the following error. If the user does exist it just throws the error below and does nothing.

Exception calling "FetchAll" with "0" argument(s): "The search filter cannot be recognized.

0

Hello,

To remedy the issue, replace the following line:
$name = $Context.GetModifiedPropertyValue("name")
with the following one:
$name = $Context.GetModifiedPropertyValue("cn")

Related questions

0 votes
1 answer

We are using the following script to track group membership changes and need the %username% field to amend if it already exists in the file location. Example: We make change ... -ItemType File # Save the report to the file Add-Content $file $report.ToString()

asked Mar 6, 2017 by willy-wally (3.2k points)
0 votes
1 answer

Hello, I am looking for assistance in modifying our user creation script. When users with multiple names are being created for example, Jesus ... "$uniqueUsername@$domaiName") $Context.LogMessage("User Logon Name: $uniqueUsername@$domaiName", "Information")

asked Sep 8, 2016 by jhair (520 points)
0 votes
1 answer

This is a long shot but is there a way to script out the creation of Custom Commands? Right now when we create a new office (which is almost 2 times a months) we speend a ... is the 1st 3 letters so if the office is in Miami it MIA-Mangers and so on.

asked Jan 14, 2020 by hgletifer (1.3k points)
0 votes
1 answer

Hi all, I have a condition during new user creation - Where the corporate email is entered into the email address field, but a custom drop-down for "Mailbox required?" is No. ... screen, and be able to save the result of this choice to a variable? Thanks all,

asked Oct 24 by dshortall (80 points)
0 votes
1 answer

I'm currently using CustomAttributeBoolean1 in order to differentiate end user and service accounts during user creation. I've added the attribute to the Property Pattern scoped for my ... a way to set the default value but have the field still be visible?

asked Jul 24 by awooten (80 points)
3,552 questions
3,242 answers
8,243 comments
547,828 users