Question when Using A Powershell Script to Create AD Users

Dear all,

I want to simply my work, so I wrote a script to crreate AD users, but unfortunately it doesn't work as designed. It's the code:

Import-Module ActiveDirectory #import AD module $TempIns = Read-Host -Prompt 'Please input a user to refer' #Offer an user for reference $OU = (Get-ADUser $TempIns -Properties *).distinguishedname.substring((Get-ADUser $TempIns -Properties *).CN.length+4) #Get OU $groups = (Get-ADPrincipalGroupMembership $TempIns).name #Get groups #======================Import CSV File================================================== #[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") #$OFDImportCSV = New-Object System.Windows.Forms.OpenFileDialog #$OFDImportCSV.ShowDialog() #$Users = Import-Csv $OFDImportCSV.FileName $Users = Import-Csv D:\ADUsers.csv #=====================End Import====================================================== foreach ($User in $Users) { #==================Define paraments================== $GivenName = ($User.'English Name' -split ' ')[0] $Surname = ($User.'English Name' -split ' ')[1] $DisplayName = $User.'English Name' $samAccountName = $GivenName+"."+$Surname $title = $User.Position $desc = $User.Position $employeeID = $User.'Employee ID' $password = $User.Password $mobile = $User.Mobile $company = $User.Company $dept = $User.Department $UPN = $samAccountName+"@microsoft.com" $Office = $User.Location $date = Get-Date #==============End definition====================== #$msg=$date + " Start create AD user " + $samAccountName Write-Output $date', Start create AD user '$samAccountName >> D:\Creation.log New-ADUser -Instance $TempIns -Path $OU -Name $DisplayName -DisplayName $DisplayName -SamAccountName $samAccountName -GivenName $GivenName -Surname $Surname -Title $title -UserPrincipalName $UPN -Company $company -Department $dept -Office $Office -ErrorVariable ADError if($ADError) { $ADError = $null Write-Output $date', Failed to created user '$samAccountName >> D:\Creation.log continue; } Set-ADAccountPassword $samAccountName -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $password -Force ) #set password Set-ADUser $samAccountName -Enabled 1 -ChangePasswordAtLogon 1 -Replace @{pager=$employeeID;Mobile=$mobile;CN=$DisplayName;sn=$GivenName} foreach( $group in $groups ) { if($group -eq 'Domain Users'){ continue; } Add-ADGroupMember $group $samAccountName } #Copy Group membership Write-Output $date', Create user '$samAccountName' successfully.' >> D:\Creation.log } #Remove-Module ActiveDirectory #exit AD module

I am really grateful if you can correct my mistakes, I am confused. Thank you in advance.


January 26th, 2015 1:05pm

Hi Chenry,

To create AD user in powershell, Please refer to the script below, and we can list the parameters of New-ADUser in $newuser and handle the error with try and catch instead in powershell:

$TempIns = Read-Host -Prompt 'Please input a user to refer' #Offer an user for reference
$OU = (Get-ADUser $TempIns -Properties *).distinguishedname.substring((Get-ADUser $TempIns -Properties *).CN.length+4) #Get OU
$Users = Import-Csv D:\ADUsers.csv 
$date = Get-Date

foreach($User in $Users){

 $GivenName = ($User.'English Name' -split ' ')[0]   
 $Surname  = ($User.'English Name' -split ' ')[1] 
 $samAccountName = $GivenName+"."+$Surname 

    $newUser=@{
	Name=$User.'English Name'
	SamAccountName = $samAccountName       
        Description=$User.Position
        GivenName=$GivenName
        surName=$Surname
	DisplayName = $User.'English Name'   
	Title = $User.Position	  
	Company = $User.Company
	Department = $User.Department
	Office =  $User.Location
	EmployeeID = $User.'Employee ID'
	MobilePhone = $User.Mobile
        UserPrincipalName=$samAccountName+"@microsoft.com"
        Path=$OU
        Enabled=$true
        ChangePasswordAtLogon=$true
        AccountPassword=(ConvertTo-SecureString $User.Password -AsPlainText -Force)
    }
    Try{
        New-ADUser @newUser -ErrorAction Stop 
        Write-Host "User $samAccountName created at $date" 
       }
    Catch{
        Write-Host "There was a problem creating User $samAccountName. The account was not created!" 
    }
}

If there is anything else regarding this issue, please feel free to post back.

Best Regards,

Anna Wang


Free Windows Admin Tool Kit Click here and download it now
January 27th, 2015 9:33am

Thank you so much, Anna. Finally I found the root cause, there's a # at the beginning of my template (D:\ADUsers.csv) header row. Now I face another questions: I need a complex password for each user. The password must meet AD password complexity policy, it means:

<quote>

 1. At least 8 characters
 2. Contain characters from three of the following four categories:
           English uppercase characters (A through Z)
           English lowercase characters (a through z)
           Base 10 digits (0 through 9)
           Non-alphabetic characters (for example, !, $, #, %)
 3. For easy-reading, these chracters are picked off: I O o l 1 0

</quote>

Before I wrote it into a file, but now I want to generate it by Powershell functions, can you tell me how can I do it?

Have a great day.

January 28th, 2015 1:39pm

Here's a way you can generate passwords with a function:

function New-Password
{
    param
    ( 
        [int] $Length = 8,
        [string] $Characters = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789_!@#$%^&*()_",
        [int] $Count = 1
    )
    
    1..$Count | foreach {
        $Bytes = New-Object "System.Byte[]" $Length
        $Random = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
        $Random.GetBytes($Bytes)
        $Result = ""
        for( $i=0; $i -lt $Length; $i++ )
        {
            $Result += $Characters[ $Bytes[$i] % $Characters.Length ]	
        }
        $Result
    }
}
This was not all my own work - I found this method on the web a couple years back. You can specify the -Count parameter if you would like to generate more than one password.

Free Windows Admin Tool Kit Click here and download it now
January 28th, 2015 6:37pm

Dear Matt,

Thank you.

Now I have a new question:

I use the script Anna provided, I need an attibute "pager", but it's not a valid parament for New-ADUser, Have I to change it by Set-ADUser -Replace @{pager=$User.'Employee ID'}?

Thank you.

February 2nd, 2015 5:08am

Hi Chenry,

Please try this way:

New-ADUser @newUser -OtherAttributes @{Pager=$User.'Employee ID'} -ErrorAction Stop 

If there is anything else regarding this issue, please feel free to post back.

Best Regards,

Anna Wang


Free Windows Admin Tool Kit Click here and download it now
February 2nd, 2015 5:26am

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics