Ad user is not creting

Hi all im using this script



Clear-Host
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Confirm:$false -Force

Add-Type -AssemblyName System.Windows.Forms

function Get-EverCGeneratedPassword ()
{
    function Get-RandomCharacters($length, $characters) { 
    $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length } 
    $private:ofs="" #Output field separator
    return [String]$characters[$random]
    }

    $passwordArray = Get-RandomCharacters -length 3 -characters 'abcdefghijkmnopqrstuvwxyz'
    $passwordArray += Get-RandomCharacters -length 3 -characters 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
    $passwordArray += Get-RandomCharacters -length 2 -characters '1234567890'
    $passwordArray += Get-RandomCharacters -length 2 -characters '~!@#$%^&*()_+=-*/\'
    
    $characterArray = $passwordArray.ToCharArray()   
    $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length     
    $outputString = -join $scrambledStringArray
    return $outputString 
}
$mailFrom = "ITRobot@alex.com"
$mailTo = "vinokura@alex.com"
#$mailuser = "alertmanager@evercompliant.com"
$smtpserver = "ex2019.alex.local"
$mailpword = convertto-SecureString -String '^PC)&Sb2y7G8#"c(' -AsPlainText -Force



$main_form = New-Object System.Windows.Forms.Form
$main_form.Text ='EverC New User Creation'

$main_form.Width = 600

$main_form.Height = 400

$main_form.AutoSize = $true

#######

$img =  [System.Drawing.Image]::Fromfile('G:\My Drive\IT\Everc-logo.png')
$companyLogo = New-Object System.Windows.Forms.PictureBox
$companyLogo.Width = $img.Size.Width
$companyLogo.Height = $img.Size.Height
$companyLogo.Image = $img
$main_form.controls.add($companyLogo)

#######

$firstNameLabel = New-Object System.Windows.Forms.Label

$firstNameLabel.Text = "First Name"

$firstNameLabel.Location  = New-Object System.Drawing.Point(10,90)

$firstNameLabel.AutoSize = $true

$main_form.Controls.Add($firstNameLabel)

############
$firstNameTextBox = New-Object System.Windows.Forms.TextBox

$firstNameTextBox.Width = 100

$firstNameTextBox.Location  = New-Object System.Drawing.Point(70,90)

$main_form.Controls.Add($firstNameTextBox)
######

$lastNameLabel = New-Object System.Windows.Forms.Label

$lastNameLabel.Text = "Last Name"

$lastNameLabel.Location  = New-Object System.Drawing.Point(10,120)

$lastNameLabel.AutoSize = $true

$main_form.Controls.Add($lastNameLabel)

############
$lastNameTextBox = New-Object System.Windows.Forms.TextBox

$lastNameTextBox.Width = 100

$lastNameTextBox.Location  = New-Object System.Drawing.Point(70,120)

$main_form.Controls.Add($lastNameTextBox)

######

$jobTitleLabel = New-Object System.Windows.Forms.Label

$jobTitleLabel.Text = "Job Title"

$jobTitleLabel.Location  = New-Object System.Drawing.Point(10,150)

$jobTitleLabel.AutoSize = $true

$main_form.Controls.Add($jobTitleLabel)

############
$jobTitleTextBox = New-Object System.Windows.Forms.TextBox

$jobTitleTextBox.Width = 100

$jobTitleTextBox.Location  = New-Object System.Drawing.Point(70,150)

$main_form.Controls.Add($jobTitleTextBox)
######

$managerLabel = New-Object System.Windows.Forms.Label

$managerLabel.Text = "Manager"

$managerLabel.Location  = New-Object System.Drawing.Point(10,180)

$managerLabel.AutoSize = $true

$main_form.Controls.Add($managerLabel)

############

############

$managerTextBox = New-Object System.Windows.Forms.TextBox

$managerTextBox.Width = 100

$managerTextBox.Location  = New-Object System.Drawing.Point(70,180)

$main_form.Controls.Add($managerTextBox)
######

$PhoneLabel = New-Object System.Windows.Forms.Label

$PhoneLabel.Text = "Phone"

$PhoneLabel.Location  = New-Object System.Drawing.Point(10,210)

$PhoneLabel.AutoSize = $true

$main_form.Controls.Add($PhoneLabel)

############
$PhoneLabelTextBox = New-Object System.Windows.Forms.TextBox

$PhoneLabelTextBox.Width = 100

$PhoneLabelTextBox.Location  = New-Object System.Drawing.Point(70,210)

$main_form.Controls.Add($PhoneLabelTextBox)
######

$userGroupsLabel = New-Object System.Windows.Forms.Label

$userGroupsLabel.Text = "User's Group(s)`nPlease mark relevant group(s) only."

$userGroupsLabel.Location  = New-Object System.Drawing.Point(200,90)

$userGroupsLabel.AutoSize = $true

$main_form.Controls.Add($userGroupsLabel)

############
$userGroupsListBox = New-Object System.Windows.Forms.CheckedListBox

$userGroupsListBox.Width = 250

$userGroupsListBox.Location  = New-Object System.Drawing.Point(200,120)

$ouDNs = @("OU=Groups,OU=Alex,DC=alex,DC=local", "OU=DL,OU=Alex,DC=alex,DC=local")
$allGroups = foreach ($ouDN in $ouDNs) {
    Get-ADGroup -Filter {objectClass -eq "group" -or objectClass -eq "msExchDynamicDistributionList"} -SearchBase $ouDN
}
foreach ($group in $allGroups)
{
    [void] $userGroupsListBox.Items.Add($group.Name)   
}


$main_form.Controls.Add($userGroupsListBox)

######

$groupsNoteLabel = New-Object System.Windows.Forms.Label

$groupsNoteLabel.Text = "Groups are used to grant access to resources, please verify carefully"

$groupsNoteLabel.ForeColor = "Red"

$groupsNoteLabel.Location  = New-Object System.Drawing.Point(200,220)

$groupsNoteLabel.AutoSize = $true

$main_form.Controls.Add($groupsNoteLabel)


#########
#########
$office365AccountLabel = New-Object System.Windows.Forms.Label
$office365AccountLabel.Text = "Office 365"

$office365AccountLabel.Location  = New-Object System.Drawing.Point(10,250)

$office365AccountLabel.AutoSize = $true

$main_form.Controls.Add($office365AccountLabel)


#########
$office365AccountCheckBox = New-Object System.Windows.Forms.CheckBox

$office365AccountCheckBox.Width = 15

$office365AccountCheckBox.Location  = New-Object System.Drawing.Point(70,245)

$main_form.Controls.Add($office365AccountCheckBox)

#####
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(10,320)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'Create User'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$main_form.AcceptButton = $OKButton
$main_form.Controls.Add($OKButton)


$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(100,320)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$main_form.CancelButton = $CancelButton
$main_form.Controls.Add($CancelButton)

######

$main_form.ShowDialog()

if ($main_form.DialogResult -eq 'Cancel') {
    [System.Windows.Forms.MessageBox]::Show("New user creation cancelled!","New User Creation Result","Ok", "Information")
    exit
}

if ($main_form.DialogResult -eq 'OK')



{
$firstName = $firstNameTextBox.Text
$firstName = $firstName.Substring(0,1).ToUpper() + $firstName.Substring(1,$firstName.Length -1)
$lastName = $lastNameTextBox.Text
$lastName = $lastName.Substring(0,1).ToUpper() + $lastName.Substring(1,$lastName.Length -1)

$jobTitle = $jobTitleTextBox.Text
$Phone = $PhoneLabelTextBox.Text

$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.com"
    $password = Get-EverCGeneratedPassword
    


    if($office365AccountCheckBox.CheckState -eq "checked"){
        $office365Creation = "True"
    }
    Else{$office365Creation = "False"}

    $newUserGroupMembership = @()
    $newUserGroupMembership = $userGroupsListBox.CheckedItems

    $Message =
    "User will be created in JumpCloud
    First Name: $($firstNameTextBox.text)
    Last Name: $($lastNameTextBox.Text)
    Phone Number: $($PhoneLabelTextBox.Text)
    Job Title: $($jobTitleTextBox.Text)
    Manager: $($managerTextBox.Text)
    Username: $username
    E-mail: $email
    Initial Password: $password
    Office 365 user: $office365Creation
    User's group membership: $($newUserGroupMembership -join ", `n")

    Make sure to save the initial password in a safe location.
    "

    ######
    ######

    $verifyDetails = [System.Windows.Forms.MessageBox]

    $Decision = $verifyDetails::Show($Message,"Verify New User Details","OkCancel", "Information")
    
    if ($Decision -eq "OK"){
        $Decision = $verifyDetails::Show("Did you remember to save the user initial password in a safe location?`nPassword: $($password)","Verify New User Details","OkCancel", "Information")
    }

    If ($Decision -eq "Cancel") {
    [System.Windows.Forms.MessageBox]::Show("New user creation operation has been terminated by user","New User Creation Terminated","Ok", "warning")
}

if ($Decision -eq "OK") {
    try {
      
      # Create the user account in Active Directory
if ($manager -ne "") {
    # If a manager is specified, include it as an attribute
$manager = Get-ADUser -Filter "SamAccountName -eq '$($manager)'" -Properties DistinguishedName
if ($manager -ne $null) {
    # If a manager is specified, include it as an attribute
    New-ADUser -Name "$firstName $lastName" -SamAccountName $username -UserPrincipalName $username -Title $jobTitle -Path "OU=Sales,DC=example,DC=com" -Manager $manager.DistinguishedName
} else {
    # If no manager is specified, create the account without the attribute
    New-ADUser -Name "$firstName $lastName" -SamAccountName $username -UserPrincipalName $username -Title $jobTitle -Path "OU=Sales,DC=example,DC=com"
}
}
        # Wait for a few seconds to allow the user account to be fully created
        Start-Sleep -Seconds 2

       

        # Add the user to any additional groups specified in $newUserGroupMembership
        foreach ($group in $newUserGroupMembership) {
            Add-ADGroupMember -Identity $g -Members $username
        }

        # Wait for a few seconds to allow group membership to be updated
        Start-Sleep -Seconds 2

        # If Office 365 creation is requested, add the user to the "All Users - Office 365 Apps" group
        if ($office365Creation) {
            Add-ADGroupMember -Identity "All Users - Office 365 Apps" -Members $username
        }

        # Wait for a few seconds to allow group membership to be updated
        Start-Sleep -Seconds 2

        # Set the initial password for the user account
        Set-ADAccountPassword -Identity $username -NewPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Reset

        # Verify that the user account was created successfully
        $user = Get-ADUser -Filter {SamAccountName -eq $username}
        if ($user.SamAccountName -eq $username) {
            # If the user account was created successfully, send a confirmation email
            $mailBody = @"
New User has been created by $currentlyLogedUser from $($currentSystem.displayName) ($($currentSystem._id))
First Name: $($firstNameTextBox.text)
Last Name: $($lastNameTextBox.Text)
Job Title: $($jobTitleTextBox.Text)
Manager: $($managerTextBox.Text)
Username: $username
E-mail: $email
Initial Password: $password
Office 365 user: $office365Creation
User's group membership: $($newUserGroupMembership -join ", `n")
"@
            Send-MailMessage -From $mailFrom -To $mailTo -Subject 'New User Creation succeeded' -Body $mailBody -SmtpServer $smtpServer -Port 587 -UseSsl -Credential $mailCredential
            Write-Host "New user $username created successfully." -ForegroundColor Green
            [System.Windows.Forms.MessageBox]::Show("New user creation completed successfully!","New User Creation Result","Ok", "Information")
        } else {
            # If the user account was not created successfully, log an error message
            Write-Host "Error: User account $username could not be created." -ForegroundColor Red
            [System.Windows.Forms.MessageBox]::Show("Error: User account $username could not be created. Please check the logs for more details.","New User Creation Result","Ok", "Error")
}
} catch {
# If an error occurs, log the error message and display an error message to the user
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
[System.Windows.Forms.MessageBox]::Show("Error creating new user. Please check the logs for more details.","New User Creation Result","Ok", "Error")
}
}

 but when i run this script the user is not created i getting message "Error: The search filter cannot be recognized"
who can help?
thank you 

That is a large script to troubleshoot. There isn’t a lot of context being provided and the little provided is wrapped in the code block:

but when i run this script the user is not created i getting message “Error: The search filter cannot be recognized”
who can help?
thank you

Search filter points to a Get that is occurring and it is not formatted properly, or null values are being provided. Initially, you need to determine the line the error is occurring on validate the filter and variables are being populated as expected.

im getting error Error: The search filter cannot be recognized

This should get you started.

Variables at lines 28 and 259 are never used. This doesn’t create errors but is not clean and can cause confusion.

$null on line 321
I don’t know that it was causing problems yet, but it jumped out as a possible issue. Not having $null on the left can cause problems. See here PossibleIncorrectComparisonWithNull - PowerShell | Microsoft Learn

What the script has and not considered best practice due to potentially causes issues

if ($manager -ne $null)

Considered best practice.

if ($null -ne $manager)

The error

Error: The search filter cannot be recognized

Is being caused by line 320

$manager = Get-ADUser -Filter "SamAccountName -eq '$($manager)'" -Properties DistinguishedName

The issue is the variable $manager has no value. You need to fix your code to both receive a value from the GUI manager field and handle when the manager field is blank.

Getting past that error actually leads you to another error.

Error: Cannot find an object with identity: 'All Users - Office 365 Apps' under: 'DC=contoso,DC=com'.

The script does not handle the "office 365"check box being unchecked, line 345 runs even if it is not checked.

thank you
I updated what you suggested
now user creating but user is disabled and i cannot see details like first name and last name in ad

Clear-Host
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Confirm:$false -Force

Add-Type -AssemblyName System.Windows.Forms

function Get-EverCGeneratedPassword ()
{
    function Get-RandomCharacters($length, $characters) { 
    $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length } 
    $private:ofs="" #Output field separator
    return [String]$characters[$random]
    }

    $passwordArray = Get-RandomCharacters -length 3 -characters 'abcdefghijkmnopqrstuvwxyz'
    $passwordArray += Get-RandomCharacters -length 3 -characters 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
    $passwordArray += Get-RandomCharacters -length 2 -characters '1234567890'
    $passwordArray += Get-RandomCharacters -length 2 -characters '~!@#$%^&*()_+=-*/\'
    
    $characterArray = $passwordArray.ToCharArray()   
    $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length     
    $outputString = -join $scrambledStringArray
    return $outputString 
}
$mailFrom = "ITRobot@alex.com"
$mailTo = "vinokura@alex.com"
#$mailuser = "alertmanager@evercompliant.com"
$smtpserver = "ex2019.alex.local"
$mailpword = convertto-SecureString -String '^PC)&Sb2y7G8#"c(' -AsPlainText -Force



$main_form = New-Object System.Windows.Forms.Form
$main_form.Text ='EverC New User Creation'

$main_form.Width = 600

$main_form.Height = 400

$main_form.AutoSize = $true

#######

$img =  [System.Drawing.Image]::Fromfile('G:\My Drive\IT\Everc-logo.png')
$companyLogo = New-Object System.Windows.Forms.PictureBox
$companyLogo.Width = $img.Size.Width
$companyLogo.Height = $img.Size.Height
$companyLogo.Image = $img
$main_form.controls.add($companyLogo)

#######

$firstNameLabel = New-Object System.Windows.Forms.Label

$firstNameLabel.Text = "First Name"

$firstNameLabel.Location  = New-Object System.Drawing.Point(10,90)

$firstNameLabel.AutoSize = $true

$main_form.Controls.Add($firstNameLabel)

############
$firstNameTextBox = New-Object System.Windows.Forms.TextBox

$firstNameTextBox.Width = 100

$firstNameTextBox.Location  = New-Object System.Drawing.Point(70,90)

$main_form.Controls.Add($firstNameTextBox)
######

$lastNameLabel = New-Object System.Windows.Forms.Label

$lastNameLabel.Text = "Last Name"

$lastNameLabel.Location  = New-Object System.Drawing.Point(10,120)

$lastNameLabel.AutoSize = $true

$main_form.Controls.Add($lastNameLabel)

############
$lastNameTextBox = New-Object System.Windows.Forms.TextBox

$lastNameTextBox.Width = 100

$lastNameTextBox.Location  = New-Object System.Drawing.Point(70,120)

$main_form.Controls.Add($lastNameTextBox)

######

$jobTitleLabel = New-Object System.Windows.Forms.Label

$jobTitleLabel.Text = "Job Title"

$jobTitleLabel.Location  = New-Object System.Drawing.Point(10,150)

$jobTitleLabel.AutoSize = $true

$main_form.Controls.Add($jobTitleLabel)

############
$jobTitleTextBox = New-Object System.Windows.Forms.TextBox

$jobTitleTextBox.Width = 100

$jobTitleTextBox.Location  = New-Object System.Drawing.Point(70,150)

$main_form.Controls.Add($jobTitleTextBox)
######

$managerLabel = New-Object System.Windows.Forms.Label

$managerLabel.Text = "Manager"

$managerLabel.Location  = New-Object System.Drawing.Point(10,180)

$managerLabel.AutoSize = $true

$main_form.Controls.Add($managerLabel)

############

############

$managerTextBox = New-Object System.Windows.Forms.TextBox

$managerTextBox.Width = 100

$managerTextBox.Location  = New-Object System.Drawing.Point(70,180)

$main_form.Controls.Add($managerTextBox)
######

$PhoneLabel = New-Object System.Windows.Forms.Label

$PhoneLabel.Text = "Phone"

$PhoneLabel.Location  = New-Object System.Drawing.Point(10,210)

$PhoneLabel.AutoSize = $true

$main_form.Controls.Add($PhoneLabel)

############
$PhoneLabelTextBox = New-Object System.Windows.Forms.TextBox

$PhoneLabelTextBox.Width = 100

$PhoneLabelTextBox.Location  = New-Object System.Drawing.Point(70,210)

$main_form.Controls.Add($PhoneLabelTextBox)
######

$userGroupsLabel = New-Object System.Windows.Forms.Label

$userGroupsLabel.Text = "User's Group(s)`nPlease mark relevant group(s) only."

$userGroupsLabel.Location  = New-Object System.Drawing.Point(200,90)

$userGroupsLabel.AutoSize = $true

$main_form.Controls.Add($userGroupsLabel)

############
$userGroupsListBox = New-Object System.Windows.Forms.CheckedListBox

$userGroupsListBox.Width = 250

$userGroupsListBox.Location  = New-Object System.Drawing.Point(200,120)

$ouDNs = @("OU=Groups,OU=Alex,DC=alex,DC=local", "OU=DL,OU=Alex,DC=alex,DC=local")
$allGroups = foreach ($ouDN in $ouDNs) {
    Get-ADGroup -Filter "objectClass -eq 'group' -or objectClass -eq 'msExchDynamicDistributionList'" -SearchBase $ouDN
}
$userGroupsListBox.Items.AddRange($allGroups.Name)
$main_form.Controls.Add($userGroupsListBox)

$main_form.Controls.Add($userGroupsListBox)

######

$groupsNoteLabel = New-Object System.Windows.Forms.Label

$groupsNoteLabel.Text = "Groups are used to grant access to resources, please verify carefully"

$groupsNoteLabel.ForeColor = "Red"

$groupsNoteLabel.Location  = New-Object System.Drawing.Point(200,220)

$groupsNoteLabel.AutoSize = $true

$main_form.Controls.Add($groupsNoteLabel)


#####
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(10,320)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'Create User'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$main_form.AcceptButton = $OKButton
$main_form.Controls.Add($OKButton)



$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(100,320)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$main_form.CancelButton = $CancelButton
$main_form.Controls.Add($CancelButton)

######

$main_form.ShowDialog()

if ($main_form.DialogResult -eq 'Cancel') {
    [System.Windows.Forms.MessageBox]::Show("New user creation cancelled!","New User Creation Result","Ok", "Information")
    exit
}

if ($main_form.DialogResult -eq 'OK')
{
    $firstName = $firstNameTextBox.Text
    $firstName = $firstName.Substring(0,1).ToUpper() + $firstName.Substring(1,$firstName.Length -1)
    $lastName = $lastNameTextBox.Text
    $lastName = $lastName.Substring(0,1).ToUpper() + $lastName.Substring(1,$lastName.Length -1)

    $jobTitle = $jobTitleTextBox.Text
    $Phone = $PhoneLabelTextBox.Text

    $i = 1
    $username = $firstName + $lastName.Substring(0,$i)
    $username = $username.ToLower()
   while ((Get-ADUser -Filter {SamAccountName -eq $username}) -ne $null) {
    $username = $firstName + $lastName.Substring(0,$i++)
    $username = $username.ToLower()
}

    $email = $username + "@alex.com"
    $password = Get-EverCGeneratedPassword
    
    $newUserGroupMembership = $userGroupsListBox.CheckedItems

    $Message =
    "User will be created in JumpCloud
    First Name: $($firstNameTextBox.text)
    Last Name: $($lastNameTextBox.Text)
    Phone Number: $($PhoneLabelTextBox.Text)
    Job Title: $($jobTitleTextBox.Text)
    Manager: $($managerTextBox.Text)
    Username: $username
    E-mail: $email
    Initial Password: $password
    User's group membership: $($newUserGroupMembership -join ", `n")

    Make sure to save the initial password in a safe location.
    "

    ######
    ######

    $verifyDetails = [System.Windows.Forms.MessageBox]

    $Decision = $verifyDetails::Show($Message,"Verify New User Details","OkCancel", "Information")
    
    if ($Decision -eq "OK"){
        $Decision = $verifyDetails::Show("Did you remember to save the user initial password in a safe location?`nPassword: $($password)","Verify New User Details","OkCancel", "Information")
    }

    If ($Decision -eq "Cancel") {
    [System.Windows.Forms.MessageBox]::Show("New user creation operation has been terminated by user","New User Creation Terminated","Ok", "warning")
}

if ($Decision -eq "OK") {
    try {
      
# Create the user account in Active Directory
if ($manager -ne "") {
    # If a manager is specified, include it as an attribute
    #$manager = Get-ADUser -Filter "SamAccountName -eq '$($manager)'" -Properties DistinguishedName
    if ($null -ne $manager) {
        # If a manager is specified, include it as an attribute
        New-ADUser -Name "$firstName $lastName" -SamAccountName $username -UserPrincipalName $username -Title $jobTitle -Path "OU=Users,OU=Alex,DC=alex,DC=local" -Manager $manager.DistinguishedName
    } else {
        # If no manager is specified, create the account without the attribute
        New-ADUser -Name "$firstName $lastName" -SamAccountName $username -UserPrincipalName $username -Title $jobTitle -Path "OU=Users,OU=Alex,DC=alex,DC=local"
    }
}

# Wait for a few seconds to allow the user account to be fully created
Start-Sleep -Seconds 2

# Add the user to any additional groups specified in $newUserGroupMembership
foreach ($group in $newUserGroupMembership) {
    Add-ADGroupMember -Identity $group -Members $username
}

# Wait for a few seconds to allow group membership to be updated
Start-Sleep -Seconds 2

# Set the initial password for the user account
Set-ADAccountPassword -Identity $username -NewPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Reset

# Verify that the user account was created successfully
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -Properties *

if ($user.SamAccountName -eq $username) {
            # If the user account was created successfully, send a confirmation email
            $mailBody = @"
New User has been created by $currentlyLogedUser from $($currentSystem.displayName) ($($currentSystem._id))
First Name: $($firstNameTextBox.text)
Last Name: $($lastNameTextBox.Text)
Job Title: $($jobTitleTextBox.Text)
Manager: $($managerTextBox.Text)
Username: $username
E-mail: $email
Initial Password: $password
User's group membership: $($newUserGroupMembership -join ", `n")
"@
            Send-MailMessage -From $mailFrom -To $mailTo -Subject 'New User Creation succeeded' -Body $mailBody -SmtpServer $smtpServer -Port 587
            Write-Host "New user $username created successfully." -ForegroundColor Green
            [System.Windows.Forms.MessageBox]::Show("New user creation completed successfully!","New User Creation Result","Ok", "Information")
        } else {
            # If the user account was not created successfully, log an error message
            Write-Host "Error: User account $username could not be created." -ForegroundColor Red
            [System.Windows.Forms.MessageBox]::Show("Error: User account $username could not be created. Please check the logs for more details.","New User Creation Result","Ok", "Error")
}
} catch {
# If an error occurs, log the error message and display an error message to the user
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
[System.Windows.Forms.MessageBox]::Show("Error creating new user. Please check the logs for more details.","New User Creation Result","Ok", "Error")
}
}
}
 

hi all i have this script

# Import ActiveDirectory module
Import-Module ActiveDirectory

# Clear the console
Clear-Host

# Set execution policy to Unrestricted
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Confirm:$false -Force

# Add System.Windows.Forms assembly
Add-Type -AssemblyName System.Windows.Forms

# Define function to generate password
function Get-AlexITGeneratedPassword ()
{
    function Get-RandomCharacters($length, $characters) 
    { 
        $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length } 
        $private:ofs="" #Output field separator
        return [String]$characters[$random]
    }

    $passwordArray = Get-RandomCharacters -length 3 -characters 'abcdefghijkmnopqrstuvwxyz'
    $passwordArray += Get-RandomCharacters -length 3 -characters 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
    $passwordArray += Get-RandomCharacters -length 2 -characters '1234567890'
    $passwordArray += Get-RandomCharacters -length 2 -characters '~!@#$%^&*()_+=-*/\'

    $characterArray = $passwordArray.ToCharArray()   
    $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length     
    $outputString = -join $scrambledStringArray
    return $outputString 
}

# Set email variables
$mailFrom = "ITRobot@alex.com"
$mailTo = "vinokura@alex.com"
$smtpserver = "ex2019.alex.local"
$mailpword = convertto-SecureString -String '^PC)&Sb2y7G8#"c(' -AsPlainText -Force


$main_form = New-Object System.Windows.Forms.Form
$main_form.Text ='AlexIT New User Creation'

$main_form.Width = 600

$main_form.Height = 400

$main_form.AutoSize = $true

#######

$img =  [System.Drawing.Image]::Fromfile('G:\My Drive\IT\Everc-logo.png')
$companyLogo = New-Object System.Windows.Forms.PictureBox
$companyLogo.Width = $img.Size.Width
$companyLogo.Height = $img.Size.Height
$companyLogo.Image = $img
$main_form.controls.add($companyLogo)

#######

$firstNameLabel = New-Object System.Windows.Forms.Label

$firstNameLabel.Text = "First Name"

$firstNameLabel.Location  = New-Object System.Drawing.Point(10,90)

$firstNameLabel.AutoSize = $true

$main_form.Controls.Add($firstNameLabel)

############
$firstNameTextBox = New-Object System.Windows.Forms.TextBox

$firstNameTextBox.Width = 100

$firstNameTextBox.Location  = New-Object System.Drawing.Point(70,90)

$main_form.Controls.Add($firstNameTextBox)
######

$lastNameLabel = New-Object System.Windows.Forms.Label

$lastNameLabel.Text = "Last Name"

$lastNameLabel.Location  = New-Object System.Drawing.Point(10,120)

$lastNameLabel.AutoSize = $true

$main_form.Controls.Add($lastNameLabel)

############
$lastNameTextBox = New-Object System.Windows.Forms.TextBox

$lastNameTextBox.Width = 100

$lastNameTextBox.Location  = New-Object System.Drawing.Point(70,120)

$main_form.Controls.Add($lastNameTextBox)

######


$jobTitleLabel = New-Object System.Windows.Forms.Label

$jobTitleLabel.Text = "Job Title"

$jobTitleLabel.Location  = New-Object System.Drawing.Point(10,150)

$jobTitleLabel.AutoSize = $true

$main_form.Controls.Add($jobTitleLabel)

############
$jobTitleTextBox = New-Object System.Windows.Forms.TextBox

$jobTitleTextBox.Width = 100

$jobTitleTextBox.Location  = New-Object System.Drawing.Point(70,150)

$main_form.Controls.Add($jobTitleTextBox)
######

$managerLabel = New-Object System.Windows.Forms.Label

$managerLabel.Text = "Manager"

$managerLabel.Location  = New-Object System.Drawing.Point(10,180)

$managerLabel.AutoSize = $true

$main_form.Controls.Add($managerLabel)

############

############

$managerTextBox = New-Object System.Windows.Forms.TextBox

$managerTextBox.Width = 100

$managerTextBox.Location  = New-Object System.Drawing.Point(70,180)

$main_form.Controls.Add($managerTextBox)
######

$PhoneLabel = New-Object System.Windows.Forms.Label

$PhoneLabel.Text = "Phone"

$PhoneLabel.Location  = New-Object System.Drawing.Point(10,210)

$PhoneLabel.AutoSize = $true

$main_form.Controls.Add($PhoneLabel)

############
$PhoneLabelTextBox = New-Object System.Windows.Forms.TextBox

$PhoneLabelTextBox.Width = 100

$PhoneLabelTextBox.Location  = New-Object System.Drawing.Point(70,210)

$main_form.Controls.Add($PhoneLabelTextBox)
######

$userGroupsLabel = New-Object System.Windows.Forms.Label

$userGroupsLabel.Text = "User's Group(s)`nPlease mark relevant group(s) only."

$userGroupsLabel.Location  = New-Object System.Drawing.Point(200,90)

$userGroupsLabel.AutoSize = $true

$main_form.Controls.Add($userGroupsLabel)

############
$userGroupsListBox = New-Object System.Windows.Forms.CheckedListBox

$userGroupsListBox.Width = 250

$userGroupsListBox.Location  = New-Object System.Drawing.Point(200,120)

$ouDNs = @("OU=Groups,OU=Alex,DC=alex,DC=local", "OU=DL,OU=Alex,DC=alex,DC=local")
$allGroups = foreach ($ouDN in $ouDNs) {
    Get-ADGroup -Filter "objectClass -eq 'group' -or objectClass -eq 'msExchDynamicDistributionList'" -SearchBase $ouDN
}
$userGroupsListBox.Items.AddRange($allGroups.Name)
$main_form.Controls.Add($userGroupsListBox)

$main_form.Controls.Add($userGroupsListBox)

######

$groupsNoteLabel = New-Object System.Windows.Forms.Label

$groupsNoteLabel.Text = "Groups are used to grant access to resources, please verify carefully"

$groupsNoteLabel.ForeColor = "Red"

$groupsNoteLabel.Location  = New-Object System.Drawing.Point(200,220)

$groupsNoteLabel.AutoSize = $true

$main_form.Controls.Add($groupsNoteLabel)


#####
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Point(10,320)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = 'Create User'
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::OK
$main_form.AcceptButton = $OKButton
$main_form.Controls.Add($OKButton)



$CancelButton = New-Object System.Windows.Forms.Button
$CancelButton.Location = New-Object System.Drawing.Point(100,320)
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
$CancelButton.Text = 'Cancel'
$CancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel
$main_form.CancelButton = $CancelButton
$main_form.Controls.Add($CancelButton)

######

$main_form.ShowDialog()

if ($main_form.DialogResult -eq 'Cancel') {
    [System.Windows.Forms.MessageBox]::Show("New user creation cancelled!","New User Creation Result","Ok", "Information")
    exit
}


if ($main_form.DialogResult -eq 'OK')
{
    $firstName = $firstNameTextBox.Text
    $firstName = $firstName.Substring(0,1).ToUpper() + $firstName.Substring(1,$firstName.Length -1)
    $lastName = $lastNameTextBox.Text
    $lastName = $lastName.Substring(0,1).ToUpper() + $lastName.Substring(1,$lastName.Length -1)

    $jobTitle = $jobTitleTextBox.Text
    $Phone = $PhoneLabelTextBox.Text

    $i = 1
    $username = $firstName + $lastName.Substring(0,$i)
    $username = $username.ToLower()
   while ($null -ne (Get-ADUser -Filter {SamAccountName -eq $username})) {
    $username = $firstName + $lastName.Substring(0,$i++)
    $username = $username.ToLower()
}

    $email = $username + "@alex.com"
    $password = Get-AlexITGeneratedPassword
    
    $newUserGroupMembership = $userGroupsListBox.CheckedItems

    $Message =
    "User will be created in AlexIT
    First Name: $($firstNameTextBox.text)
    Last Name: $($lastNameTextBox.Text)
    Phone Number: $($PhoneLabelTextBox.Text)
    Job Title: $($jobTitleTextBox.Text)
    Manager: $($managerTextBox.Text)
    Username: $username
    E-mail: $email
    Initial Password: $password
    User's group membership: $($newUserGroupMembership -join ", `n")

    Make sure to save the initial password in a safe location.
    "

    ######
    ######

    $verifyDetails = [System.Windows.Forms.MessageBox]

    $Decision = $verifyDetails::Show($Message,"Verify New User Details","OkCancel", "Information")
    
    if ($Decision -eq "OK"){
        $Decision = $verifyDetails::Show("Did you remember to save the user initial password in a safe location?`nPassword: $($password)","Verify New User Details","OkCancel", "Information")
    }

    If ($Decision -eq "Cancel") {
    [System.Windows.Forms.MessageBox]::Show("New user creation operation has been terminated by user","New User Creation Terminated","Ok", "warning")
}

if ($Decision -eq "OK") {
    try {


      
# Check if the $manager variable has a value
if ([string]::IsNullOrWhiteSpace($manager)) {
    # If no manager is specified, create the account without the attribute
    New-ADUser -Name "$firstName $lastName" -SamAccountName $username -UserPrincipalName $username -Title $jobTitle -Path "OU=Users,OU=Alex,DC=alex,DC=local"
} else {
    # Retrieve the manager's distinguished name
    $managerDN = (Get-ADUser -Filter "SamAccountName -eq '$manager'" -Properties DistinguishedName).DistinguishedName
    if ([string]::IsNullOrWhiteSpace($managerDN)) {
        Write-Host "Manager not found. Creating user account without manager attribute."
        # If no manager is found, create the account without the attribute
        New-ADUser -Name "$firstName $lastName" -SamAccountName $username -UserPrincipalName $username -Title $jobTitle -Path "OU=Users,OU=Alex,DC=alex,DC=local"
    } else {
        # If a manager is specified and found, include it as an attribute
        New-ADUser -Name "$firstName $lastName" -SamAccountName $username -UserPrincipalName $username -Title $jobTitle -Path "OU=Users,OU=Alex,DC=alex,DC=local" -Manager $managerDN
    }
}



# Wait for a few seconds to allow the user account to be fully created
Start-Sleep -Seconds 2

# Add the user to any additional groups specified in $newUserGroupMembership
foreach ($group in $newUserGroupMembership) {
    Add-ADGroupMember -Identity $group -Members $username
}

# Wait for a few seconds to allow group membership to be updated
Start-Sleep -Seconds 2

# Set the initial password for the user account
Set-ADAccountPassword -Identity $username -NewPassword (ConvertTo-SecureString $password -AsPlainText -Force) -Reset

# Enable the user account
Enable-ADAccount -Identity $username

# Set the "User must change password at next logon" property to true
Set-ADUser -Identity $username -ChangePasswordAtLogon $true

# Verify that the user account was created successfully
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -Properties *
if ($user.SamAccountName -eq $username) {
            # If the user account was created successfully, send a confirmation email
            $mailBody = @"
New User has been created.
First Name: $($firstNameTextBox.text)
Last Name: $($lastNameTextBox.Text)
Job Title: $($jobTitleTextBox.Text)
Manager: $($managerTextBox.Text)
Username: $username
E-mail: $email
Initial Password: $password
User's group membership: $($newUserGroupMembership -join ", `n")
"@
            Send-MailMessage -From $mailFrom -To $mailTo -Subject 'New User Creation succeeded' -Body $mailBody -SmtpServer $smtpServer -Port 587
           
            [System.Windows.Forms.MessageBox]::Show("New user creation completed successfully!","New User Creation Result","Ok", "Information")
        } else {
            # If the user account was not created successfully, log an error message
    
            [System.Windows.Forms.MessageBox]::Show("Error: User account $username could not be created. Please check the logs for more details.","New User Creation Result","Ok", "Error")
}
} catch {
# If an error occurs, log the error message and display an error message to the user
Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
[System.Windows.Forms.MessageBox]::Show("Error creating new user. Please check the logs for more details.","New User Creation Result","Ok", "Error")
}
}
}

the user is created but i cannot see the properties of the user
why?

Which properties can’t you see?

I only took a cursory look at your script because it’s so long, but you’re only setting these:

Name, SamAccountName, UserPrincipalName, Title, Path, and maybe Manager.

That’s really the bare minimum. You’re not populating GivenName, Surname, DisplayName, Description etc. so all of those would be blank.

You mention in your previous post that the account is created disabled. I would check that your command to set the password is working properly.
You can’t enable an account until you’ve set a password.

yes i know i did it
now user created withouth any details name last name and set

As matt-bloomfield pointed out, you are collecting the information, you are just not using it.

Frist Name (GivenName) or Last Name (Surname) are not being set at account creation time.

UPN is not complete. Missing domain (example of missing piece @domain.com)

Script assumes you are provided with SamAccountName of the manager, but shouldn’t do that. You might want to rethink how you are taking user input and then finding the manager. One way is to provide more information to the user for what is being looked for.

Telephone is not set

I suppose display name isn’t technically required, but it is generally a helpful attribute to populate, which the script does not.

Here is what the script creates as of the latest version of the script.

PS C:\PSS> Get-ADUser bugsb -Properties title,manager,telephoneNumber,displayName

DisplayName       : 
DistinguishedName : CN=Bugs Bunny,OU=Alex,DC=contoso,DC=com
Enabled           : True
GivenName         : 
Manager           : 
Name              : Bugs Bunny
ObjectClass       : user
ObjectGUID        : a887489f-fe70-4c70-870e-c2a8ab1626fe
SamAccountName    : bugsb
SID               : S-1-5-21-2285398822-2117556293-3919152467-1116
Surname           : 
Title             : Sales
UserPrincipalName : bugsb

To polish the script as it is now:

  1. update the use of new-aduser to set first and last name.
  2. update the use of new-aduser to set the telephone number
  3. review how you are collecting manager info. could be as simple as updating the info gathering window to be more specific via the label for the manager field that sam account is needed.
  4. fix ow the upn is set so that it is complete
  5. consider adding Display Name