none
Create csv for creating bulk users in Active Directory using PowerShell

    Question

  • Hi team,

    I need to create around 50 users. I have checked the forum and tried several steps but I am unable to create the csv as per company's requirement.

    The display name format we use is the first six letters of the first name, first letter of the last name and the five digit employee number. For eg.: if users name is Rahul Sharma and his employee code is 03121, his display name should be rahuls03121.

    Also, other details like Designation, Manager, Location etc should get populated.

    I am attaching the picture for your reference. Please revert for any questions.

    Thursday, August 17, 2017 7:58 AM

All replies

  • Here's an article on importing users in bulk using CSV files that might help: http://www.adaxes.com/blog/how-to-bulk-import-ad-users-from-csv.html
    • Edited by kuingul Friday, August 18, 2017 10:59 AM
    Friday, August 18, 2017 10:59 AM
  • Friday, August 18, 2017 3:22 PM
    Moderator
  • Hello,

    you can create nice table in excel making the first row the property names. You can get the correct property names by running help new-aduser, which will list all available parameters. Copy the names of those parameters into you excel spreadsheet and add user data underneath the first row. 

    Save the file as a .csv and then $users = import-csv <path_to_file>

    $users | new-aduser

    Please let me know if you have any questions. Thank you.

    Saturday, August 19, 2017 4:48 AM
  • This would be your code:

    #advanced Script
    #Solution to : https://www.experts-exchange.com/questions/29048293/I-need-to-add-user-by-csv-file-to-AD-with-PowerShell.html
        [CmdletBinding()]
        param(
            [Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$true)]$CsvFilePath="C:\Users\Administrator\Desktop\Another CSV\CsvFile.csv",
            [Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$true)]$Ou="test"
        )
    
    #region Functions
    function Write-Log{
        [CmdletBinding()]
        #[Alias('wl')]
        [OutputType([int])]
        Param(
                # The string to be written to the log.
                [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true, Position=0)] [ValidateNotNullOrEmpty()] [Alias("LogContent")] [string]$Message,
                # The path to the log file.
                [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true,Position=1)] [Alias('LogPath')] [string]$Path=$global:DefaultLog,
                [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true,Position=2)] [ValidateSet("Error","Warn","Info","Load","Execute")] [string]$Level="Info",
                [Parameter(Mandatory=$false)] [switch]$NoClobber
        )
    
         Process{
            
            if ((Test-Path $Path) -AND $NoClobber) {
                Write-Warning "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name."
                Return
                }
    
            # If attempting to write to a log file in a folder/path that doesn't exist
            # to create the file include path.
            elseif (!(Test-Path $Path)) {
                Write-Verbose "Creating $Path."
                $NewLogFile = New-Item $Path -Force -ItemType File
                }
    
            else {
                # Nothing to see here yet.
                }
    
            # Now do the logging and additional output based on $Level
            switch ($Level) {
                'Error' {
                    Write-Warning $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") ERROR: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Warn' {
                    Write-Warning $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") WARNING: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Info' {
                    Write-Host $Message -ForegroundColor Green
                    Write-Verbose $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") INFO: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Load' {
                    Write-Host $Message -ForegroundColor Magenta
                    Write-Verbose $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") LOAD: `t $Message" | Out-File -FilePath $Path -Append
                    }
                'Execute' {
                    Write-Host $Message -ForegroundColor Green
                    Write-Verbose $Message
                    Write-Output "$(Get-Date -Format "yyyy-MM-dd HH:mm:ss") EXEC: `t $Message" | Out-File -FilePath $Path -Append
                    }
                }
        }
    }
    function Get-DistinguishedName{
        [CmdletBinding()]
        param(
            [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]$OUName
        )
        BEGIN{ }
        PROCESS{
            $GetOUinAD = Get-ADOrganizationalUnit -Filter {Name -like $OUName}
    
        }
        END{
            return $GetOUinAD.DistinguishedName
        }
    }
    function Get-Length{
        [CmdletBinding()]
        param(
            [Parameter(Position=0,Mandatory=$true)]$string, #string
            [Parameter(Position=1,Mandatory=$true)]$Chars #number of chars that it should take
        )
        BEGIN{
    
            if( $Chars -le $string.Length){
                $CharsToTake=$Chars
            }
            else{
                $CharsToTake = $string.length
            }
    
    
        }
        PROCESS{}
        END{
            return $CharsToTake
        }
    
    }
    
    function FindCNManager{
        [CmdletBinding()]
        param(
            [Parameter(Position=0,Mandatory=$true,ValueFromPipeline=$true)]$Id
        )
        BEGIN{
            
         }
        PROCESS{
            $user =Get-ADUser -Filter { displayname -like $Id}
        }
        END{
            return $user.DistinguishedName
        }
    }
    #endregion Functions
    
    #Clean Up VariableS
    $CleanUpVar=@()
    $CleanUpGlobal=@()
    
    
    #GLOBALs 
    $global:ScriptLocation = $(get-location).Path
    $global:DefaultLog = "$global:ScriptLocation\CreateUsers.log"
    $CleanUpGlobal+="ScriptLocation"
    $CleanUpGlobal+="DefaultLog"
    
    Write-Log -Level Info -Message "######################   * Start Script *   ######################"
    
    #Importing AD Module if it's not loaded
    # Import AD PowerShell module
    if( (Get-Command Get-ADUser).count -lt 1 ){
        try{
            Write-Log -Level Load -Message "Loading AD PS Module"
            Import-Module ActiveDirectory -Cmdlet New-ADUser,Get-ADUser,Set-ADUser
        }
        catch{
            $ErrorMessage = $_.Exception.Message
            Write-Log -Level Error -Message "There's no ActiveDirectory Module installed on the local computer, please use a computer with AD module installed ``n`r$ErrorMessage"
            exit(-1)
        }
    }
    else{
        Write-Log -Level Info -Message "The Active Directory Module is already loaded"
    }
    
    # Common variables
    $OuDn = Get-DistinguishedName -OUName $ou
    $AllAdUsers = (Get-ADUser -Filter *).SamAccountName
    
    #CLEANUP
    $CleanUpVar+="OuDn"
    $CleanUpVar+="AllAdUsers"
    
    # Import data from csv file
    Write-Log -Level Load -Message "Loading CSV File in $CsvFilePath"
    $LoadedCsv = Import-Csv $CsvFilePath
    
    #CLEANUP
    $CleanUpVar+="LoadedCsv"
    if($LoadedCsv.count -gt 0){
        $CleanUpVar+="FirstName"
        $CleanUpVar+="LastName"
        $CleanUpVar+="FNLength"
        $CleanUpVar+="LNLength"
        $CleanUpVar+="UserLogonName"
        $CleanUpVar+="EncryptedPassword"
        $CleanUpVar+="Team"
        $CleanUpVar+="manager"
        
    }
    
     foreach ($user in $LoadedCsv) {
        
        #The display name format we use is the first six letters of the first name, first letter of the last name and the five digit employee number. For eg.: 
        $FirstName = $user.Name.Split(' ')[0]
        $LastName = $user.Name.Split(' ')[1]
        $FNLength=  Get-Length $FirstName 6
        $LNLength = Get-Length $LastName 1
    
        #if users name is Rahul Sharma and his employee code is 03121, his display name should be rahuls03121
        $UserLogonName = $FirstName.Substring(0,$FNLength).Tolower() + $LastName.substring(0,$LNLength).Tolower() + $user."Employee Code".Substring(0,5).ToLower()  
        $EncryptedPassword = ConvertTo-SecureString $($user.Password) -AsPlainText -Force
        $Team = if(! $user.'Team/Report'){ $null}else{$user.'Team/Report'}
    
        $manager= if(! $Team){$null}else{ FindCNManager $Team}
        #$HomeFolder = Join-Path -Path $HomeFolderPath -ChildPath $UserLogonName
    
        #Create new AD user account
        if ($AllAdUsers -notcontains $UserLogonName) {
            Write-Log -Level info -Message "Creating user $UserLogonName"
          
    
            New-ADUser -SamAccountName $UserLogonName `
                        -Name $user.Name `
                        -GivenName $FirstName `
                        -Surname $LastName `
                        -DisplayName "$FirstName $LastName" `
                        -UserPrincipalName $user."Email address" `
                        -AccountPassword $EncryptedPassword `
                        -City $user.Location `
                        -Company $user.Company `
                        -Department $user.Department `
                        -EmployeeID $user.'Employee Code' `
                        -Path $OuDn `
                        -Enabled $true `
                        -Manager $manager `
                        -Title $user.Designation `
                        -CannotChangePassword $true `
                        -ChangePasswordAtLogon $true
        }
        else {
            Write-Log -Level Warn -Message "$UserLogonName already exists"
        }
     }
    
     #clean up
    Write-Log -Level Info "Cleaning up variables"
    Write-Log -Level Info -Message "######################   * Stript Ended *   ######################"
    $CleanUpVar| ForEach-Object{
    	Remove-Variable $_
    	}
    $CleanUpGlobal | ForEach-Object{
    	Remove-Variable -Scope global $_
    }
    Remove-Variable CleanUpGlobal,CleanUpVar


    And in your CSV you need to create 1st the managers and then the people that depend on them. (ex: if  person A reports to person B: you would need to create the person B 1first in the CSV  and then the people A).

    This is the CSV

    Name,Designation,Department,Team/Report,Location,Company,DateOfJoining,EmailID,Personal Mobile Number,Employee Code,Password
    Sanjay Kumar,CEO,HR,,Mumbai,ABCD Pvt Ltd,01-JAN-15,sanjay.kumar,5599955999,DCASW310,Password1
    Rahul Sharma,Officer,HR,Sanjay Kumar,Mumbai,ABCD Pvt Ltd,14-aug-17,rahul.sharma,9955599555,ABCD03190,Password2

    The Output is:


    • Proposed as answer by j0rt3g4 Saturday, August 19, 2017 7:40 AM
    • Edited by j0rt3g4 Saturday, August 19, 2017 7:43 AM
    Saturday, August 19, 2017 7:39 AM
  • Hey man, Thanks for your time and efforts.

    When you say "in your CSV you need to create 1st the managers", will this create a new user ID for the manager? 

    Also, Rahul's ID should be rahuls03190, not rahulsabcd0. Should I do something else for this outcome?

    I appreciate your response.

    Thursday, August 24, 2017 12:15 PM
  • "In your CSV you need to create 1st the managers" 

    MEANING: The managers need to be at the top of the CSV. (that what I meant by other words).

    and about the name of the rahulWHATEVEr, just correct it in the CSV. that was an example. I'm pretty sure you can replace and put the correct name where it should be in the CSV file.


    • Edited by j0rt3g4 Saturday, November 11, 2017 9:13 AM
    Saturday, November 11, 2017 8:43 AM