Question : Powershell script to create AD accounts from spreadsheet

Hey all.. I'm looking for a script (preferrably Powershell since Im still learning it) to create 100+ accounts in AD from an Excel spreadsheet.  We need to pull the usually columns for attributes such as username, password, company, phone, etc.. but also 3 specific fields that are under the Attribute Editor tab, specifically Employee Type, Division and EmployeeID.

I know vbscripts abound, but I'm kinda leaning towards Powershell just because I'm learning it right now.  However if PS can't handle this then I'm all ears on an alternative.

Thanks!

Answer : Powershell script to create AD accounts from spreadsheet

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
## define constants
$domainstr = ",dc=starking,dc=org"
$domainnb = "starking"             ## domain netbios name
$domain = "starking.org"

$ADs_UF_NORMAL_ACCOUNT = 512   ## enables account and sets password required

## get default passsword - encrypted so not stored in script
$defaultPassword = Read-Host "Please enter default Password" -asSecureString

## get the list of users from the CSV file
## if need other user properties can add to CSV
## could speed processing by sortng user list by OU but need code 
## to handle change of OU.  This is simpler as an example

Import-csv users.txt | foreach {

## create user name
	$strusr = $_.Last + " " + $_.First
	$strusr	

 	$ldapstr = "LDAP://OU=" + $_.OU + $domainstr

	$target = [ADSI] $ldapstr
	$newuser = $target.create("user", "cn=" + $strusr)
	$newuser.SetInfo()
	
        $userid = $_.first[0]+$_.first[1]+$_.last
	if ($userid.length -gt 20){$userid = $userid.substring(0,20)}
       	
	$newuser.samaccountname = $userid.ToString()
	$newuser.givenName =  $_.first
	$newuser.sn = $_.last
	$newuser.displayName = $_.last + " " + $_.first
	$newuser.userPrincipalName = $_.first[0]+$_.first[1]+$_.last + "@" + $domain
	$newuser.SetInfo()

	$newuser.SetPassword($defaultPassword.ToString())

## normal user that requires password & is enabled
	$newuser.userAccountControl = $ADs_UF_NORMAL_ACCOUNT
	$newuser.SetInfo()

# set User must change password at next logon flag
	$newuser.pwdLastSet = 0
	$newuser.SetInfo()

## now set the country
	$newuser.c = $_.Country
	$newuser.SetInfo()


	Write-Host "Created Account for: "  $newuser.Displayname

}
Random Solutions  
 
programming4us programming4us