Active Directory User Management Powershell Script

An essential guide for IT professionals to automate user creation, modification and management in Active Directory, saving time and reducing human error.

In this Guide:

Introduction

In today’s fast paced IT world manually managing user accounts in Active Directory (AD) is a time consuming and error prone process. This guide provides a Active Directory user management script to automate tasks such as creating new users, modifying attributes or bulk disabling accounts. This is a must have for user onboarding, offboarding and large scale data updates making it a critical tool for IT pros and system administrators to increase efficiency and security.

Background

Creating a new user account manually involves multiple steps: open the Active Directory Users and Computers (ADUC) console, fill out many fields (name, department, email), set a password and assign group memberships. For organizations with high employee turnover or frequent user data changes this becomes a repetitive and boring task. An automate AD accounts script solves this problem by allowing you to manage users in bulk using data from a simple CSV file, so you can have consistency and accuracy across all accounts. This reduces the risk of typos and configuration errors that can lead to security vulnerabilities or service interruptions.

Script Code

Here is a versatile PowerShell script that can bulk-create new users from a CSV file.

New-ADUsersFromCSV.ps1
Copy to clipboard
# -----------------------------------------------------------------------------
# Script Name: New-ADUsersFromCSV.ps1
# Description: Automates the creation of new Active Directory user accounts from a CSV file.
# Author: Team Zecurit
# Date: September 8, 2025
# -----------------------------------------------------------------------------

# Prerequisites: Active Directory module for PowerShell must be installed.

# PARAMETERS:
# -CsvPath: Path to the CSV file containing user data.
# -Password: The temporary password to be set for all new users.
# -OuPath: The Distinguished Name (DN) of the Organizational Unit (OU) where new users will be created.

param(
    [Parameter(Mandatory=$true)]
    [string]$CsvPath,

    [Parameter(Mandatory=$true)]
    [string]$Password,

    [Parameter(Mandatory=$true)]
    [string]$OuPath
)

# Import the Active Directory module
Import-Module ActiveDirectory

# Read the CSV file and iterate through each user record
try {
    $users = Import-Csv -Path $CsvPath
}
catch {
    Write-Host "Error: Could not import the CSV file. Please check the path and file format." -ForegroundColor Red
    exit
}

# Process each user
foreach ($user in $users) {
    # Check if a user with the same SamAccountName already exists
    if (Get-ADUser -Filter "SamAccountName -eq '$($user.SamAccountName)'") {
        Write-Host "User $($user.SamAccountName) already exists. Skipping." -ForegroundColor Yellow
        continue
    }
    
    # Create the new user account
    try {
        New-ADUser -Name "$($user.FirstName) $($user.LastName)" `
            -GivenName $user.FirstName `
            -Surname $user.LastName `
            -SamAccountName $user.SamAccountName `
            -UserPrincipalName "$($user.SamAccountName)@$((Get-ADDomain).DnsRoot)" `
            -Path $OuPath `
            -Enabled $true `
            -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) `
            -ChangePasswordAtLogon $true
        
        Write-Host "Successfully created user $($user.SamAccountName)." -ForegroundColor Green
        
        # Add the user to groups from the CSV file (optional)
        if ($user.Groups) {
            $user.Groups.Split(',') | ForEach-Object {
                $groupName = $_.Trim()
                if (Get-ADGroup -Filter "Name -eq '$groupName'") {
                    Add-ADGroupMember -Identity $groupName -Members $user.SamAccountName
                    Write-Host "Added $($user.SamAccountName) to group $groupName." -ForegroundColor Green
                }
                else {
                    Write-Host "Group '$groupName' not found. Skipping." -ForegroundColor Yellow
                }
            }
        }
    }
    catch {
        Write-Host "Error creating user $($user.SamAccountName): $($_.Exception.Message)" -ForegroundColor Red
    }
}

Write-Host "Script execution complete."

Detailed Breakdown

  • Connecting to Active Directory: The script begins by using Import-Module ActiveDirectory. This is a crucial first step that loads the necessary cmdlets to interact with your AD environment. You must have the Remote Server Administration Tools (RSAT) installed on the machine where you run the script to access these cmdlets.

  • Reading Data from a CSV File: The script uses the Import-Csv cmdlet to read user data from a comma-separated values (CSV) file. This is a best practice for bulk user creation. Each row in the CSV represents a new user, and the columns (headers) correspond to the user attributes you want to set, such as FirstName, LastName, and SamAccountName.

  • Performing Actions: The script iterates through each row of the imported CSV file. For each user, it performs a check to see if the account already exists using Get-ADUser. This prevents duplicate user creation. The core of the script is the New-ADUser cmdlet, which creates the new account and sets attributes like the display name, UPN, and a temporary password. It also includes an optional section to add the new user to AD groups listed in the CSV.

  • Error Handling: The script uses try...catch blocks to gracefully handle potential errors, such as a missing CSV file or a user that already exists. This ensures that the script continues to run even if it encounters an issue with a single user record.

Use Cases

  • New Employee Onboarding: Add new employee info to a CSV and run this user onboarding script to create their AD account, set their initial password and add them to the right groups. This is how you automate AD accounts.

  • Offboarding: A modified version of this script can be used for offboarding. Instead of creating users, it can read a list of terminated employees from a CSV and disable their accounts, move them to another OU or remove them from all groups.

  • Bulk User Updates: If you need to update a specific user attribute for a large number of users (e.g. update department or office location) you can export the user data, modify the CSV and use a script with the Set-ADUser cmdlet to do the updates in one go.

Conclusion

Automating Active Directory user management with PowerShell is a game changer that will save you hours and hours and make your IT environment more secure. By using a standard script you ensure every new user account is configured the same way as your company’s policies. For those new to AD scripting the Active Directory PowerShell module is a must have tool.

You can find comprehensive documentation on all its cmdlets on Microsoft Learn. For more related topics, check out our guides on Auditing User Login History and Managing System Reboots. .

Deploy this script across your Endpoints with Zecurit

Upload this script to Zecurit's Script Repository and execute it across hundreds of endpoints in minutes. Support for PowerShell, Bash, Python,and more with full audit trails and scheduling.

Frequently Asked Questions (FAQs)

  • What permissions do I need to run this script?

    You must run this script with a user account that has the necessary permissions to create and modify user objects in the target Organizational Unit (OU) in Active Directory. Typically, this requires being a member of the Domain Admins or Account Operators group.

  • How do I install the Active Directory PowerShell module?

    On a domain-joined machine, you can install the module using the Install-WindowsFeature cmdlet in an elevated PowerShell session: Install-WindowsFeature RSAT-AD-PowerShell. On Windows 10/11, you can install it from Settings > Apps > Optional Features.

  • Can this script create users in different OUs?

    Yes, but the current script is configured to create all users in a single OU. To create users in different OUs, you would need to add a column for OuPath in your CSV file and modify the script to read this path for each user record.