Not able create user with employee number

Hi all,
I have a script that should create a user with an employee number a should check if the employee number is exciting to create a new employee number.
but this stop is no working for me

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 (($AccountSamAccountName) -and ($Password -match "$AccountSamAccountName")) {
        return $false
    }
   if ($AccountDisplayName) {
    $tokens = $AccountDisplayName.Split(",.-,_ #`t")
    foreach ($token in $tokens) {
        if (($token) -and ($Password -match "$token")) {
            return $false
        }
    }
}
   
   
    return $true   
   
}


function Get-AvailableEmployeeNumber {
param(
    [int]$EmployeeNumber,
    [string[]]$AllNum
)

if($AllNum -contains $EmployeeNumber){
    Get-AvailableEmployeeNumber -EmployeeNumber ($EmployeeNumber + 1) -AllNum $AllNum

}
else{
    $EmployeeNumber
}

}



# Grab Variables from User
$ADPath = "OU=Users,OU=Alex,DC=alex,DC=local"

    

# Grab Variables from User
$firstname = Read-Host -Prompt "Enter First Name"

# Stop by empty first name
while (!($firstname -eq "")){

$lastname = Read-Host  -Prompt  "Enter Last Name"
 
do {
    try {
        [int]$EmployeeNumber = Read-Host "Enter Employee Number"
    }
    catch [System.Management.Automation.PSInvalidCastException] {
        Write-Warning "You can only use numbers!"
        
    }
}
until (($EmployeeNumber -or $EmployeeNumber -eq 0) -and $EmployeeNumber -match "^[0-9]*$")

if (-not(Get-ADUser -filter "EmployeeNumber -eq '$EmployeeNumber'")) {
    write-output "$EmployeeNumber is available."
}
else {
    Write-Warning "EmployeeNumber '$EmployeeNumber' is already in use."
    $allNum = 
    [Int32[]]($((Get-ADUser -Filter * -Properties EmployeeNumber).EmployeeNumber)) |
    Sort-Object -Descending 

    $newNum = Get-AvailableEmployeeNumber -EmployeeNumber $EmployeeNumber -AllNum $allNum
    Write-Output "The next Available EmployeeNumber is '$newNum'"

}


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

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

}

# Set username
$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" 
if (Get-ADUser -Filter "surname -eq '$lastname' -and givenname -eq '$firstname'")

{
  
# Create the AD User
New-ADUser `
-Name "$firstname $lastname ($EmployeeNumber)" `
-GivenName $firstname `
-Surname $lastname `
-EmployeeNumber $EmployeeNumber `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1   
}
else
{
   # Create the AD User
New-ADUser `
-Name "$firstname $lastname" `
-GivenName $firstname `
-Surname $lastname `
-EmployeeNumber $EmployeeNumber `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1   
}





Write-Host  -ForegroundColor Green "The user"$username" created successfully."

Remove-Variable -Name 'EmployeeNumber'

$firstname = Read-Host -Prompt "Enter First Name"

}

Write-Host -ForegroundColor Red "Done, Thank You"



any idea why is not working?

thank you

Alex,

that’s a big chunk of code. Where exactly does it stop? Please don’t make us debugging your complete script. :wink:

And BTW: Since you seem to anyway increase the number the user of this script enters if it’s already there why not assigning a new employee number automatically by increasing the last/highest found employee number? That would make your script a little more robust.

i treid to that but it wasnt working so i use the function

Maybe you gave up to easily. :wink: Why don’t we try to make this working?

i thouth this is helping forum
so i thouth that maybe someone will hlep me
but i see that you the only one whos here an you not willing to help
so i will look for some other help

I just offered to help you!?!?

1 Like

not feeling like if ,
if I knew what to do I wasn’t asking questions in this post

Of course. But you have to be willing to help us helping you as well. So either you tell us where exactly your code is not working as expected or you post the approach you coulnd’t complete and we could try to make it work.

ok i have this function

function Get-AvailableEmployeeNumber {
param(
    [int]$EmployeeNumber,
    [string[]]$AllNum
)

if($AllNum -contains $EmployeeNumber){
    Get-AvailableEmployeeNumber -EmployeeNumber ($EmployeeNumber + 1) -AllNum $AllNum

}
else{
    $EmployeeNumber
}

}

its chekcs if employee number exsite or not
and if yes its give message next free number is 5

but in my script its not create the employee with free employee number
this the script to create new user

New-ADUser `
-Name "$firstname $lastname ($EmployeeNumber)" `
-GivenName $firstname `
-Surname $lastname `
-EmployeeNumber $EmployeeNumber `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1   

and idont know whot to add this function to employee number
any idea?

OK, assumed the employeeNumbers in your company are plain integers with no alphabetical or special charachters the following should be all you need.

It queries the AD for all employees and determines the highest employeeNumber. Then it increases it by one and that’s it. :wink:

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
}

If you have an OU in your AD where you have all your user accounts I hihgly recommend to use a SearchBase pointing to this OU as this reduces the stress you put on your AD with this kind of query. :point_up_2:t4:

Regardless of that … please read the help for

Using backticks to be able to add line breaks is a really bad style and error prone btw.
Your function New-AdUser would look like this:

$NewAdUserProperties = @{
    Name              = "$firstname $lastname ($EmployeeNumber)"
    GivenName         = $firstname
    Surname           = $lastname
    EmployeeNumber    = $EmployeeNumber
    Displayname       = "$FirstName $lastname"
    UserPrincipalName = $email
    SamAccountName    = $username
    AccountPassword   = (ConvertTo-SecureString $passwordAsPlainTextForce)
    Path              = $ADPath
    Enabled           = $true
}
New-ADUser @NewAdUserProperties
1 Like

Thank you for you answer
i will read about splatting but unforcedly its still not create user with a free employee number

i think its becuse of

EmployeeNumber    = $EmployeeNumber

i tried to ernter her EmployeeNumber = $EmployeeNumber+1

but its wasnt working

any idea?

The function i suggested has another name than yours. You have to adapt your code to it when you use it like I suggested it!!! :wink:

i know i changed you function to my name

unction EmployeeNumber {
    $SearchBase = 
        'OU=Users,OU=Alex,DC=alex,DC=local'
    $EmployeeNumber = 
        Get-ADUser -Filter * -SearchBase $SearchBase -Properties EmployeeNumber | 
            Sort-Object -Property EmployeeNumber | 
                Select-Object -Last 1 -ExpandProperty EmployeeNumber 
    ($EmployeeNumber -as [Int32]) + 1
}
do {
    try {
        [int]$EmployeeNumber = Read-Host "Enter Employee Number"
    }
    catch [System.Management.Automation.PSInvalidCastException] {
        Write-Warning "You can only use numbers!"
        
    }
}
until (($EmployeeNumber -or $EmployeeNumber -eq 0) -and $EmployeeNumber -match "^[0-9]*$")

if (-not(Get-ADUser -filter "EmployeeNumber -eq '$EmployeeNumber'")) {
    write-output "$EmployeeNumber is available."
}
else {
    Write-Warning "EmployeeNumber '$EmployeeNumber' is already in use."
    $allNum = 
    [Int32[]]($((Get-ADUser -Filter * -Properties EmployeeNumber).EmployeeNumber)) |
    Sort-Object -Descending 

    $newNum = EmployeeNumber -EmployeeNumber $EmployeeNumber -AllNum $allNum
    Write-Output "The next Available EmployeeNumber is '$newNum'"

}

still not creating user :frowning:

The function I suggested does not need any input at all. So you can drop all the code you used to get the input from the user and all that other stuff. With the name you used for the function (EmployeeNumber) all you need is this:

$newNum = EmployeeNumber

nothing more !!!

its good but its not creating user 1 by 1 and just random

I realy don’t understand what you mean.

That is not helpful.

sorry
i want it to create user with employee number
1 by 1
for expamle
alex employeenumber 1
Olaf employeenumber 2

hope that its explandebale

The function I suggested determines the next unused employeenumber. So you don’t need to provide a particular employeenumber at all. If you insist to provide a particular employeenumber you have to use your own code. Is that really so hard to understand?

Do you have a completely empty AD with no user accounts yet?

yes i have i couple of user

OK. And I assume they already have employeenumbers, right? So when you use my suggestion the newly created user will automatically get an employeenumber 1 number higher than the highest already existing employeenumber.