Bulk ADUser Import

The tutorial importing users via Excel spreadsheet works great!

The New-ADUser cmdlet is useful for creating new user accounts in Active Directory. However, it has limitations when it comes to certain attributes like “info,” “mailnickname,” and “msExchHideFromAddressLists.” These attributes are not directly available as parameters in the New-ADUser command.

I am able to update these attributes using Set-ADUser, but the problem is if the “username” already exists, it updates these attributes for the account that already exists when it should not update that account at all. By no means should any existing account get modified, so this is problematic.

This is a problem, since we will have several Jr IT members mass importing users using the script, and they can potentially enter user data for existing users.

The challenge arises when existing users are involved. If a username already exists, using Set-ADUser will update the attributes for that account.

The script is displayed below:

Import Active Directory module

Import-Module ActiveDirectory

Open file dialog

Load Windows Forms

[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null

Create and show open file dialog

$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.InitialDirectory = $StartDir
$dialog.Filter = “CSV (*.csv)| *.csv”
$dialog.ShowDialog() | Out-Null

Get file path

$CSVFile = $dialog.FileName

Import file into variable

Lets make sure the file path was valid

If the file path is not valid, then exit the script

if ([System.IO.File]::Exists($CSVFile)) {
Write-Host “Importing CSV…”
$CSV = Import-Csv -LiteralPath “$CSVFile”
} else {
Write-Host “File path specified was not valid”
Exit
}

Lets iterate over each line in the CSV file

foreach($user in $CSV)
{

# Format their username
$UserName = "$($user.'First Name'[0])$($user.'Last Name')"
$UserName = $Username.Replace(" ", "")

# Password
$SecurePassword = $user.'New Password'
#$SecurePassword = ConvertTo-SecureString "HeloSkill1122!@#" -AsPlainText -Force

#Create AD User
 New-ADUser -Name "$($user.'First Name') $($user.'Last Name')" `
            -path "$($user.'Organizational Unit')" `
            -GivenName $user.'First Name' `
            -Surname $user.'Last Name' `
            -UserPrincipalName $UserName `
            -SamAccountName $UserName `
            -DisplayName $user.'display name' `
            -Description "$($user.'Description')" `
            -Office $user.'Office ' `
            -HomePage $user.'Home Page' `
            -City $user.'City' `
            -State $user.'State' `
            -Country $user.'Country' `
            -EmailAddress $user.'Email Address' `
            -Title $user.'Job Title' `
            -Manager $user.'Supervisor' `
            -HomeDrive $user.'Home Drive' `
            -HomeDirectory $user.'Home Directory' `
            -MobilePhone $user.'Mobile Phone' `
            -Company $user.'Company Name' `
            -ChangePasswordAtLogon $false `
            -PasswordNeverExpires $True `
            -CannotChangePassword $True `
            -AccountPassword (ConvertTo-SecureString $SecurePassword -AsPlainText -Force) `
            -Enabled $([System.Convert]::ToBoolean($user.Enabled))
               
# Add Telephone tab \Notes entry:
Set-ADUser -identity $UserName -Replace @{info="$($user.'First Name') $($user.'Last Name')" }


# Add Mail Enabled Attributes

if (-not [string]::IsNullOrWhiteSpace($UserName.mailNickname)) {
if ($UserName.mailNickname -ne “”) {
Write-Host “MailNickName already exists. No action taken.”
Set-ADUser -Identity $UserName -Replace @{mailNickname=$UserName.mailNickname}
} else {
Write-Host “MailNickName is ‘’. No update needed.”
}}

# Add Mail Enabled Attributes
Set-ADUser -identity $UserName -Replace @{extensionAttribute5="$($user.'First Name') $($user.'Last Name')" }               
#Set-ADUser -identity $UserName -Replace @{mailNickname= $UserName }
Set-ADUser -identity $UserName -Replace @{msExchHideFromAddressLists= $True }


# Write to host that we created a new user
  Write-Host "Created $Username / $($user.'Email Address')"

# If groups is not null... then iterate over groups (if any were specified) and add user to groups
if ($user.'AddToGroups(csv)' -ne "") {
       $user.'AddToGroups(csv)'.Split(",") | ForEach {
         Add-ADGroupMember -Identity $_ -Members "$Username"
         Write-Host "Added $UserName to $_ group" # Log to console
                }
    }

# Write to host that we created the user
#Write-Host "Created user $Username with groups $($User.'Add Groups (csv)')"

}

Hi @erikm

You can make your script does not update existing users by checking if a user account already exists before attempting to create a new one or updating using the IF ELSE inside the ForEach.

Ricardo

I tried that, but it made no difference. Maybe I do not have the right logic.

The following is an example script that shows the logic:

$username = "exampleUsername" # Replace this with the actual username variable

# Check if the user already exists in Active Directory
$userExists = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue

if ($userExists -eq $null) {
    # If the user doesn't exist, create the new user account
    $newUserParams = @{
        SamAccountName = $username
        # Add other necessary parameters here
    }
    New-ADUser @newUserParams

    # After creating the user, set additional attributes with Set-ADUser
    Set-ADUser -Identity $username -Add @{
        info = "This is some info"
        mailnickname = "exampleNickname"
        # Note: Custom attributes like 'msExchHideFromAddressLists' might require
        # direct interaction with Exchange or additional AD modules
    }

    Write-Output "User '$username' created successfully."
} else {
    Write-Output "User '$username' already exists. No action was taken."
}