Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Active Directory Powershell: Create bulk users from CSV file

Creating bulk multiple user accounts on Active Directory Users and Computers mmc console is very boring and tough task also it is most of the time consuming and error prone tend to be lots of mistakes. If same task is done using automation it will be interesting and happen in less time. Active directory Powershell is best way to automate the task of importing users from excel file. 

Download script and csv file sample
download new-aduseraccount fake account inventory list in excel csv

My CSV file contains below AD user properties, I tried to cover and take all properties as much as possible. If you would like to add more properties follow Microsoft official link. You will have add the same in script and header column in CSV. Below is example of one user.

NamePatrick Heninghem active directory powershell user properties all attributes and classes filled up new-aduser 
DisplayNamePatrick Heninghem
GivenNamePatrick
SurnameHeninghem
SamAccountNamePH6558
UserPrincipalName[email protected]
EmployeeID6558
AccountPasswordPaTo@6558
DescriptionEmployee
EmailAddress[email protected]
Enabled$True
MobilePhone184.192.5.227
Companyvcloud-lab.com
OfficeDevelopment Center
DepartmentTesting
DivisionSoftware
OrganizationCider
OfficePhone339692762
StreetAddress2392 Cameron Road
CityHIGH BRIDGE
StateWisconsin
CountryUS
PostalCode54846
Pathou=New,dc=vcloud-lab,dc=com
ProfilePath\\vcloud-lab.com\Profiles\%username%

To execute ps1 scripts follow this blog Different ways to bypass Powershell execution policy :.ps1 cannot be loaded because running scripts is disabled. Next I have kept my both the script in C:\temp folder location, change the location to folder using cd c:\temp command. I am running script and only providing csv file path.

.\New-AdUserAccount.ps1 -Path C:\temp\employees.csv

Active Directory Powershell  New-Aduser, domain controller new-aduseraccount, Ad user, users from csv file, enable-adaccount -identity, set-aduser, dsa.msc, ad users and computers, organization unit.

In next example if you are connecting to remote domain, I am giving explicit domain name and credential.

.\New-AdUserAccount.ps1 -Path C:\temp\employees.csv -Domain vCloud-lab.com -Credential 

Active Directory Powershell  New-Aduser, domain controller new-aduseraccount, Ad user, users from csv file, enable-adaccount -identity, set-aduser, best powershell function advanced usage teach powershell free

This code and CSV is available on Github.

#requires -version 3
<#
.SYNOPSIS
    Create new user account in Active Directory.
.DESCRIPTION
    The New-AdUserAccount cmdlet creates new user accounts on active directory domain controller from CSV file. It asks for parameter valid CSV file path, Optional Active directory domain name and Credential. This cmdlet uses
.PARAMETER Path
    Prompts you for CSV file path. There are 2 alias CSV and File, This is mandetory parameter and require valid path.
.PARAMETER Domain
    This is active directory domain name where you want to connect. 
.PARAMETER Credential
    Popups for active directory username password, supply domain admin user account for authentication.
.INPUTS
    [String]
    [Switch]
.OUTPUTS
    Output is on console directly.
.NOTES
    Version:        1.0
    Author:         Kunal Udapi
    Creation Date:  12 June 2017
    Purpose/Change: Bulk user account creation in Microsoft Active Directory domain from Excel/csv.
    Useful URLs: http://vcloud-lab.com/entries/active-directory/powershell-installing-and-configuring-active-directory-and-dns-server
.EXAMPLE
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv

    This command create bulk users account in logged in domain from CSV file, It uses default logged in Credentials.
.Example
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv -Domain vCloud-lab.com -Credential

    Here I have used all the parameters Path with user information, Domain name and Credentials.
.EXAMPLE
    PS C:\>New-AdUserAccount -Path C:\temp\employees.csv -Domain vCloud-lab.com
#>

[CmdletBinding(SupportsShouldProcess=$True,
    ConfirmImpact='Medium',
    HelpURI='http://vcloud-lab.com',
    DefaultParameterSetName='File')]
Param
(
    [parameter(ParameterSetName = 'File', Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
    [parameter(ParameterSetName = 'Credential', Position=0, Mandatory=$true)]
    [alias('CSV', 'File')]
    [ValidateScript({
        If(Test-Path $_){$true}else{throw "Invalid path given: $_"}
        })]
    [String]$Path,
    [Parameter(ParameterSetName='Credential', Position=1, Mandatory=$True)]
    [alias('ADServer', 'DomainName')]
    [String]$Domain,
    [Parameter(ParameterSetName='Credential')]
    [Switch]$Credential
)
#$Path = 'C:\temp\employees.csv'
if ($Credential.IsPresent -eq $True) {
    $Cred = Get-Credential -Message 'Type domain credentials to connect remote AD' -UserName (WhoAmI)
}
Import-Csv -Path $Path | foreach -Begin {
    try {
        Import-Module ActiveDirectory -ErrorAction Stop
    }
    catch {
        Write-host "Missing....Install ActiveDirectory Powershell feature -- RSAT (Remote Server Administration). Cannot Create Accounts" -BackgroundColor DarkRed
        Break
    }

} -Process {
    $UserProp = @{ 
            Name = $_.Name
            SamAccountName = $_.SamAccountName 
            UserPrincipalName = $_.UserPrincipalName 
            GivenName = $_.GivenName 
            DisplayName = $_.DisplayName 
            Surname = $_.Surname 
            AccountPassword = (ConvertTo-SecureString -AsPlainText $_.AccountPassword -Force) 
            Description = $_.Description
            EmployeeID = $_.EmployeeID 
            EmailAddress = $_.EmailAddress
            Path = $_.Path 
            MobilePhone = $_.MobilePhone
            Company = $_.Company
            Office = $_.Office 
            Department =  $_.Department 
            Division = $_.Division 
            Organization = $_.Organization 
            OfficePhone = $_.OfficePhone 
            StreetAddress = $_.StreetAddress
            City = $_.City
            State = $_.State
            Country = $_.Country
            PostalCode = $_.PostalCode
            ProfilePath = $_.ProfilePath
            ErrorAction = 'Stop'
    }
    try {
        $Name = $_.Name
        Write-Host "Processing account $Name" -NoNewline -BackgroundColor Gray
        switch ($PsCmdlet.ParameterSetName) {
            'Credential' {
                if ($Credential.IsPresent -eq $false) {
                    New-ADUser @UserProp -Server $Domain
                }
                else {
                    New-ADUser @UserProp -Server $Domain -Credential $Cred
                }
                Break
            }
            'File' {
                New-ADUser @UserProp; break
            }
        }
            Enable-ADAccount -Identity $_.SamAccountName -ErrorAction Stop
            Set-ADUser -Identity $_.SamAccountName -ChangePasswordAtLogon $True
            Write-Host "....Account $Name successfully created" -BackgroundColor DarkGreen
    }
    catch {
        Write-Host "....Processing $Name failed" -BackgroundColor DarkRed
    }
} -End {}

Useful articles
POWERSHELL: INSTALLING AND CONFIGURING ACTIVE DIRECTORY 
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE (CHANGE) MANAGER NAME IN ORGANIZATION TAB OF USER
POWERSHELL ACTIVE DIRECTORY: ADD OR UPDATE PROXYADDRESSES IN USER PROPERTIES ATTRIBUTE EDITOR
Powershell one liner: Create multiple user accounts

Go Back



Comment

Blog Search

Page Views

12085906

Follow me on Blogarama