0 votes

I am trying to create a Script power Shell for creating users with a South American standard.

I need to use the first part of firstname + the first part of last name without the suffixes.

For example: First Name: John LastName: da Silva de Souza

expected username: joao.silva.

I'm trying the script below but adaxes returns that the user already exists, even if it doesn't exist.

# Lista de sufixos comuns para remover
$ignoreWords = @("da", "de", "do", "dos", "das", "e")

# Função para remover acentos e caracteres especiais
function Remove-Accents {
    param ($text)
    $accentedChars = "áàãâäéèêëíìîïóòõôöúùûüçñÁÀÃÂÄÉÈËÍÌÎÏÓÒÕÔÖÚÙÛÜÇÑ"
    $replacementChars = "aaaaaeeeeiiiiooooouuuucnAAAAAEEEEIIIIOOOOOUUUUCN"

    for ($i = 0; $i -lt $accentedChars.Length; $i++) {
        $text = $text -replace $accentedChars[$i], $replacementChars[$i]
    }
    return $text
}

# Função para verificar se o usuário já existe
function UserExists($username) {
    $searcher = New-Object DirectoryServices.DirectorySearcher
    $searcher.Filter = "(&(objectClass=user)(sAMAccountName=$username))"
    $result = $searcher.FindOne()
    return $null -ne $result
}

# Obtém os valores do usuário
$firstName = "%firstname%"
$lastName = "%lastname%"

# Pega a primeira palavra do primeiro nome
$firstNamePart = ($firstName -split "\s+")[0]

# Divide o sobrenome e encontra a primeira palavra válida
$lastNameWords = $lastName -split "\s+"
$lastNamePart = ""

foreach ($word in $lastNameWords) {
    if ($ignoreWords -notcontains ($word.ToLower())) {
        $lastNamePart = $word
        break
    }
}

# Remove acentos e converte para minúsculas
$firstNamePart = Remove-Accents $firstNamePart
$lastNamePart = Remove-Accents $lastNamePart

# Monta o nome de usuário inicial
$username = ("$firstNamePart.$lastNamePart").ToLower()

# Verifica se o usuário já existe e incrementa se necessário
$index = 1
$originalUsername = $username
while (UserExists($username)) {
    $username = "$originalUsername$index"
    $index++
}

# Define o domínio fixo
$domainName = "cloveritbr.local"
$userPrincipalName = "$username@$domainName"

# Log para debug
Write-Output "Username gerado: $username"
Write-Output "UPN gerado: $userPrincipalName"

# Define os atributos no Adaxes
$Context.TargetObject.Put("sAMAccountName", $username)
$Context.TargetObject.Put("userPrincipalName", $userPrincipalName)

# Aplica as mudanças
$Context.TargetObject.SetInfo()
ago by (20 points)

1 Answer

0 votes
ago by (15.5k points)

Hello,

As far as we understand, the script is executed in a business rule triggering Before creating a user. If so, you should not use the Put and SetInfo methods in scripts executed in business rules that trigger Before creating objects as the object does not exist yet. Instead, you need to use the SetModifiedPropertyValue method to update the values provided on the Create form. For more details on how to validate/modify user input using a script, have a look at the following tutorial: https://www.adaxes.com/help/ValidateModifyUserInputWithScript.

Additionally, it is recommended to use criteria in the searcher instead of an LDAP filter. The following repository article should be helpful: https://www.adaxes.com/script-repository/check-whether-email-and-username-are-unique-s347.htm.

Lastly, the Write-Output cmdlet is not supported in Adaxes. To add custom messages to the execution log, you can use the LogMessage method of the ExecuteScriptContext class.

Related questions

0 votes
1 answer

I'm working on user deprovision and need to re-assign a user's home directory to the manager's home directory after disabling. I found a PowerShell script on this site to ... retrieve the same for the Manager? I'm a PowerShell novice, so excuse my ignorance.

asked Feb 26, 2021 by mkvidera (60 points)
0 votes
1 answer

Using this built in function: There is no option to change the domain on the user account, however this is not the domain we use for UPN. However after creating a user, you can change it but trying to avoid going back into the object.

asked Apr 14, 2023 by mightycabal (1.0k points)
0 votes
0 answers

Trying to configure a custom launcher in Thycotic Secret Server that will launch Adaxes on the user's local machine with the username and password passed as parameters. Has anyone made this work?

asked May 20, 2022 by amillard (20 points)
0 votes
1 answer

I want to remove special characters on the onboarding web form for username and mail before clicking Finish. Using a script like on the rule "Before User Creation" seems to to do the change to late and you can not verify the email adress before created.

asked Dec 27, 2021 by joem (20 points)
0 votes
0 answers

Hi We try to achieve a script where Adaxes replaces all umlauts in the username and mail adress and also checks for duplicate usernames. ... $email Context.SetModifiedPropertyValue("mailNickname", $username) $Context.SetModifiedPropertyValue("mail", $email)

asked Nov 11, 2020 by maca (100 points)
3,634 questions
3,322 answers
8,398 comments
548,787 users