Tuesday, August 4, 2015

Bulk Import Users from CSV

There are number of scripts about this available, but here is my version of bulk-import users from csv file.

<#.Synopsis
This to import users to contoso.local domain from csv file by default. You can also configure different domain.

CSV File Format:

Name,samAccountName,ParentOu,Description,Password,UserGroup

NOTE!! ParentOu Format "OU=SubOrganisationalUnit,OU=OrganisationalUnit,DC=Domain,DC=local"

.Description
Writen by Miikka Kallberg
.Parameter FilePath
Path to CSV File
.Parameter csvfile
CSV File name
.Parameter DomainName
Type domain name
.Example
.\bulkimportusers.ps1 -FilePath c:\temp\ -csvfile marvin.csv
This will export users from c:\temp\marvin.csv to contoso.local domain

.\bulkimportusers.ps1 -FilePath c:\temp\ -csvfile marvin.csv -Domain whatnow.local domain
This will import users from c:\temp\marvin.csv to whatnow.local domain

#>

Param([String]
[Parameter(Mandatory=$true)]
$FilePath='',
[Parameter(Mandatory=$true)]
$csvfile='',
[String]
$Domainname='contoso.local')
# Import active directory module for running AD cmdlets
Import-Module activedirectory

#Store the data from ADUsers.csv in the $ADUsers variable
$ADUsers = Import-csv "$FilePath\$csvfile" 

#Loop through each row containing user details in the CSV file 
foreach ($User in $ADUsers)
{
#Read user data from each field in each row and assign the data to a variable as below
$Username  = $User.name
$Password  = $User.password
$Firstname  = $User.name
$Lastname  = $User.name
$Descripte  = $User.Description
$UserGroup      = $User.UserGroup
$OU  = $User.ParentOu #This field refers to the OU the user account is to be created in
    

#Check to see if the user already exists in AD
if (Get-ADUser -F {SamAccountName -eq $Username})
{
 #If user does exist, give a warning
 Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
#User does not exist then proceed to create the new user account
        #Account will be created in then Users OU.
New-ADUser -SamAccountName $Username -UserPrincipalName "$Username@$DomainName" -Name $Lastname -Description $Descripte -Path $OU -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true
    
    #Add New User to UserGroup
    Add-ADGroupMember -Identity $UserGroup -Members $Username
}
}


1 comment:

  1. Does it work in Windows 2016 Server? I am having trouble running the powershell script, basically with errors like:
    Canmpt validate argument on parameter 'Name', the argument is null or empty.

    ReplyDelete