Not able create user with employee number

you really good with PS and thank you for you help.
but i got lost
i deleted all the script that releated to employee number as you told me and just left your function
and now its not create emploee number at all

Could you post the complete code like it is now … like you just tried?

sure

Import-Module ActiveDirectory
Function Test-PasswordForDomain {
    Param (
        [Parameter(Mandatory=$true)][string]$Password,
        [Parameter(Mandatory=$false)][string]$AccountSamAccountName = "",
        [Parameter(Mandatory=$false)][string]$AccountDisplayName,
        [Microsoft.ActiveDirectory.Management.ADEntity]$PasswordPolicy = (Get-ADDefaultDomainPasswordPolicy -ErrorAction SilentlyContinue)
    )

    If ($Password.Length -lt $PasswordPolicy.MinPasswordLength) {
        return $false
    }


   if (($username) -and ($Password -match "$username")) {
        return $false
    }
   if ($AccountDisplayName) {
    $tokens = $AccountDisplayName.Split(",.-,_ #`t")
    foreach ($token in $tokens) {
        if (($token) -and ($Password -match "$token")) {
            return $false
        }
    }
}
   
   
    return $true   
   
}

function New-EmployeeNumber {
    $SearchBase = 
        'OU=users,DC=contoso,DC=com'
    $LastEmployeeNumber = 
        Get-ADUser -Filter * -SearchBase $SearchBase -Properties EmployeeNumber | 
            Sort-Object -Property EmployeeNumber | 
                Select-Object -Last 1 -ExpandProperty EmployeeNumber 
    ($LastEmployeeNumber -as [Int32]) + 1
}


$ADPath = "OU=Users,OU=Alex,DC=alex,DC=local"   

$firstname = Read-Host -Prompt "Enter First Name"
# Stop by empty first name
while (!($firstname -eq "")){

$lastname  = Read-Host -Prompt "Enter Last Name"
 

$password = Read-Host -Prompt "Enter password"

while(!(Test-PasswordForDomain -Password $password)){
    write-host -ForegroundColor Yellow "Password complexity error!!!"
    $password = Read-Host -Prompt "Enter password"

}


$dn = "CN=$firstname $lastname,$ADPath"

try {
    Get-ADUser -Identity $dn
    $name = "$firstname  $lastname ($EmployeeNumber)"
}
catch{
    $name = "$firstname $lastname"
}

$i = 1
$username = "$firstName$($lastName.Substring(0,$i))"
$username = $username.ToLower()

while ((Get-ADUser -filter {SamAccountName -eq $username}).SamAccountName -eq $username) {
    $username = "$firstName$($lastName.Substring(0,$i++))"
    $username = $username.ToLower()
}

$email = "$username@alex.local"

$params = @{
    Name              = $name
    GivenName         = $firstname 
    Surname           = $lastname 
    Displayname       = $name
    UserPrincipalName = $email
    SamAccountName    = $username  
    AccountPassword   = (ConvertTo-SecureString $password -AsPlainText -Force)
    Path              = $ADPath 
    Enabled           = $true 
}


New-ADUser @params




$Name = $username
$Searcher = [ADSISearcher]"(sAMAccountName=$Name)"
$Results = $Searcher.FindOne()
If ($Results -eq $Null) {Write-Host  -ForegroundColor DarkRed "The user"$username" not created."}
Else {Write-Host  -ForegroundColor Green "The user"$username" created successfully."}



$firstname = Read-Host -Prompt "Enter First Name"
}
Write-Host -ForegroundColor Red "Done, Thank You"

The following code is a suggestion. It is untested but I understood you are testing in a test environment anyway. So you should test it as it is! :point_up_2:t4: :wink:
If this code does what you need you should start to try to improve one detail at a time. If the first improvement works - start to improve the next detail and so on … :wink:

Clear-Host
$firstname = Read-Host -Prompt 'Enter First Name'
$lastname = Read-Host -Prompt 'Enter Last Name'

$SearchBase = 'OU=Users,OU=Alex,DC=alex,DC=local'

$PWLength = (Get-ADDefaultDomainPasswordPolicy).MinPasswordLength
$RandomPassword = [System.Web.Security.Membership]::GeneratePassword($PWLength, 3)
$AllCurrentUsers = Get-ADUser -Filter * -SearchBase $SearchBase -Properties EmployeeNumber
$NewEmployeeNumber = (($AllCurrentUsers.EmployeeNumber | Sort-Object | Select-Object -Last 1) -as [int32]) + 1

$i = 0
do {
    $i++
    $UserName = "$firstName$($lastName.Substring(0,$i))"
} until ($UserName -notin $AllCurrentUsers.sAMAccountName)

$email = "$username@alex.local"

$params = @{
    Name              = "$firstname  $lastname ($NewEmployeeNumber)"
    Displayname       = "$firstname $lastname"
    GivenName         = $firstname 
    Surname           = $lastname 
    UserPrincipalName = $email
    SamAccountName    = $username  
    AccountPassword   = (ConvertTo-SecureString $RandomPassword -AsPlainText -Force)
    Path              = $SearchBase 
    Enabled           = $true
    EmployeeNumber    = $NewEmployeeNumber
}
New-ADUser @params

Write-Host "`nCreated new AD user with the following attributes:"
$params

Write-Host "`nThe random password for the newly created user is '" -NoNewline
Write-Host  $($RandomPassword) -ForegroundColor Green -NoNewline
Write-Host "'."

ok thank you very much

tried that not working :frowning:

That’s not helpful at all.

Thank you Olaf issue is fixed now

Thanks for the reply. :+1:t4: I’m glad to hear that. :slightly_smiling_face:

You may share your solution to help other looking for the same or a similar problem. :point_up_2:t4: