Powershell : Add student users to AD with an excel file
Powershell. or powerHell…well sometimes. I think it has got to do with lack of knowledge about this scripting technique. The more I am working with it the more i am starting to love it. Very powerfull commands to do more with less. Since the migration to exchange 2010 and windows 2008 R2 we are discovering the power of powershell. Now I’ve converted some of my scripts from VBS to powershell. In this article I have created a script to add student users to Active Directory while using a Excel xlsx file and NOT using Quest AD commandlets.
####################################################################
# PowerShell Script for to add STUDENTS users to Active Directory #
# #
# Version: 0.2 #
# #
# Requirements: #
# 1. Powershell with Exchange 2010 CMDlets #
# 2. Permissions on Exchange 2010 and Active Directory #
# 3. Excel 2007 Installed #
# 4. Excel file with the following Columns and data: #
# #
# Column 1 (A) : Last Name #
# Column 2 (B) : Middle Name (like van, de, or blank) #
# Column 3 (C) : First Name #
# Column 4 (D) : Login Name (like 22222) #
# Column 5 (E) : Class (like 4K1) #
# Column 6 (F) : Sector (VMBO, HVWO, PRO) #
# Column 7 (G) : Password #
# #
# Changelog: #
# 0.1 First version Richard #
# 0.2 Add user check Richard #
# #
####################################################################
$strExcelFile = "C:\Scripts\students.xlsx"
$strADDomainName = "domainname.local"
$strDC = "servername"
$strExchangeDB = "EX-DB"
$strExchangeSMTP = "@companyname.nl"
$strADUserLogonScriptHVWO = "Hvwo-student.vbs"
$strADUserProfPathHVWO = "\\servername\Profiles$\studentprofileHvwo"
$strADUserOUHVWO = [ADSI] "LDAP://servername.domainname.local:389/OU=Students,OU=Users,OU=HavoVwo,DC=domainname,DC=local"
$strADUserOUHVWOShort = ",OU=Students,OU=Users,OU=HavoVwo,DC=domainname,DC=local"
$strADUserGroupHVWO = [ADSI] "LDAP://servername.domainname.local:389/CN=Students HavoVwo,OU=Students,OU=groups,OU=HavoVwo,DC=domainname,DC=local"
$strADUserLogonScriptPRO = "Pro-student.vbs"
$strADUserProfPathPRO = "\\servername\Profiles$\studentprofilePro"
$strADUserOUPRO = [ADSI] "LDAP://servername.domainname.local:389/OU=Students,OU=Users,OU=Pro,DC=domainname,DC=local"
$strADUserOUPROShort = ",OU=Students,OU=Users,OU=Pro,DC=domainname,DC=local"
$strADUserGroupPRO = [ADSI] "LDAP://servername.domainname.local:389/CN=Students PRO,OU=Students,OU=groups,OU=Pro,DC=domainname,DC=local"
$strADUserLogonScriptVMBO = "Vmbo-student.vbs"
$strADUserProfPathVMBO = "\\servername\Profiles$\studentprofileVmbo"
$strADUserOUVMBO = [ADSI] "LDAP://servername.domainname.local:389/OU=Students,OU=Users,OU=Vmbo,DC=domainname,DC=local"
$strADUserOUVMBOShort = ",OU=Students,OU=Users,OU=Vmbo,DC=domainname,DC=local"
$strADUserGroupVMBO = [ADSI] "LDAP://servername.domainname.local:389/CN=Students VMBO,OU=Students,OU=groups,OU=Vmbo,DC=domainname,DC=local"
####################################################################[
# FUNCTIONS #
####################################################################
function addHVWOuser {
#check if user exists
$Status = (Check-ADUser -username $strADUserAlias).Status
If ($Status -eq 1) {Write-Host "User:" $strADUserAlias "allready exists!"}
Else {
#create user with settings
$newUser = $strADUserOUHVWO.Create("user",$CN)
$newUser.put("sAMAccountName", $strADUserAlias)
$newUser.put("GivenName", $strADUserFirstName)
$newUser.put("SN", $strADUserLastName)
$newUser.put("displayName", $strADUserFullName)
$newUser.put("initials", $strADUserInitials)
$newUser.put("description", $strADUserDiscription)
$newUser.put("profilePath", $strADUserProfPathHVWO)
$newUser.put("scriptPath", $strADUserLogonScriptHVWO)
$newUser.put("userPrincipalName", $strADUserPrincipalName)
$newUser.SetInfo()
$newUser.PsBase.Invoke("SetPassword", $strADUserPassword)
$newUser.PsBase.InvokeSet("AccountDisabled", $false)
$newUser.SetInfo()
#Set password never expires
New-Variable ADS_UF_DONT_EXPIRE_PASSWD 0x10000 -Option Constant
[int]$flag=$newUser.useraccountcontrol[0]
$newUser.useraccountcontrol=$flag -bor $ADS_UF_DONT_EXPIRE_PASSWD
$newUser.SetInfo()
#Set password cannot be changed
set-passwordchange $newUser.distinguishedname -deny
#wait for user to be created
Start-Sleep -Seconds 10
#Add user to AD Group
$strADUserGroupHVWO.add("LDAP://" + $strDC + "." + $strADDomainName + ":389/" + $CN + $strADUserOUHVWOShort)
#create mailbox and configure mailbox settings
Enable-Mailbox -Identity $strADUserFullName -Alias $strADUserAlias -Database $strExchangeDB -PrimarySmtpAddress $strADUserEmailAddress -ActiveSyncMailboxPolicy 'Default' -DomainController $strDC
Set-CASMailbox -Identity $strADUserFullName -MAPIEnabled $false -POPEnabled $false -ImapEnabled $false –ActiveSyncEnabled $false -DomainController $strDC
Set-Mailbox -Identity $strADUserFullName -HiddenFromAddressListsEnabled $true -DomainController $strDC
}
}
function addPROuser {
#check if user exists
$Status = (Check-ADUser -username $strADUserAlias).Status
If ($Status -eq 1) {Write-Host "User:" $strADUserAlias "allready exists!"}
Else {
#create user with settings
$newUser = $strADUserOUPRO.Create("user",$CN)
$newUser.put("sAMAccountName", $strADUserAlias)
$newUser.put("GivenName", $strADUserFirstName)
$newUser.put("SN", $strADUserLastName)
$newUser.put("displayName", $strADUserFullName)
$newUser.put("initials", $strADUserInitials)
$newUser.put("description", $strADUserDiscription)
$newUser.put("profilePath", $strADUserProfPathPRO)
$newUser.put("scriptPath", $strADUserLogonScriptPRO)
$newUser.put("userPrincipalName", $strADUserPrincipalName)
$newUser.SetInfo()
$newUser.PsBase.Invoke("SetPassword", $strADUserPassword)
$newUser.PsBase.InvokeSet("AccountDisabled", $false)
$newUser.SetInfo()
#Set password never expires
New-Variable ADS_UF_DONT_EXPIRE_PASSWD 0x10000 -Option Constant
[int]$flag=$newUser.useraccountcontrol[0]
$newUser.useraccountcontrol=$flag -bor $ADS_UF_DONT_EXPIRE_PASSWD
$newUser.SetInfo()
#Set password cannot be changed
set-passwordchange $newUser.distinguishedname -deny
#wait for user to be created
Start-Sleep -Seconds 10
#Add user to AD Groups
$strADUserGroupPRO.add("LDAP://" + $strDC + "." + $strADDomainName + ":389/" + $CN + $strADUserOUPROShort)
$strADUserGroupVMBO.add("LDAP://" + $strDC + "." + $strADDomainName + ":389/" + $CN + $strADUserOUPROShort)
#create mailbox and configure mailbox settings
Enable-Mailbox -Identity $strADUserFullName -Alias $strADUserAlias -Database $strExchangeDB -PrimarySmtpAddress $strADUserEmailAddress -ActiveSyncMailboxPolicy 'Default' -DomainController $strDC
Set-CASMailbox -Identity $strADUserFullName -MAPIEnabled $false -POPEnabled $false -ImapEnabled $false –ActiveSyncEnabled $false -DomainController $strDC
Set-Mailbox -Identity $strADUserFullName -HiddenFromAddressListsEnabled $true -DomainController $strDC
}
}
function addVMBOuser {
#check if user exists
$Status = (Check-ADUser -username $strADUserAlias).Status
If ($Status -eq 1) {Write-Host "User:" $strADUserAlias "allready exists!"}
Else {
#create user with settings
$newUser = $strADUserOUVMBO.Create("user",$CN)
$newUser.put("sAMAccountName", $strADUserAlias)
$newUser.put("GivenName", $strADUserFirstName)
$newUser.put("SN", $strADUserLastName)
$newUser.put("displayName", $strADUserFullName)
$newUser.put("initials", $strADUserAlias)
$newUser.put("description", $strADUserDiscription)
$newUser.put("profilePath", $strADUserProfPathVMBO)
$newUser.put("scriptPath", $strADUserLogonScriptVMBO)
$newUser.put("userPrincipalName", $strADUserPrincipalName)
$newUser.SetInfo()
$newUser.PsBase.Invoke("SetPassword", $strADUserPassword)
$newUser.PsBase.InvokeSet("AccountDisabled", $false)
$newUser.Put("pwdLastSet", 0)
$newUser.SetInfo()
#Set password never expires
New-Variable ADS_UF_DONT_EXPIRE_PASSWD 0x10000 -Option Constant
[int]$flag=$newUser.useraccountcontrol[0]
$newUser.useraccountcontrol=$flag -bor $ADS_UF_DONT_EXPIRE_PASSWD
$newUser.SetInfo()
#Set password cannot be changed
set-passwordchange $newUser.distinguishedname -deny
#wait for user to be created
Start-Sleep -Seconds 10
#Add user to AD Group
$strADUserGroupVMBO.add("LDAP://" + $strDC + "." + $strADDomainName + ":389/" + $CN + $strADUserOUVMBOShort)
#create mailbox and configure mailbox settings
Enable-Mailbox -Identity $strADUserFullName -Alias $strADUserAlias -Database $strExchangeDB -PrimarySmtpAddress $strADUserEmailAddress -ActiveSyncMailboxPolicy 'Default' -DomainController $strDC
Set-CASMailbox -Identity $strADUserFullName -MAPIEnabled $false -POPEnabled $false -ImapEnabled $false –ActiveSyncEnabled $false -DomainController $strDC
Set-Mailbox -Identity $strADUserFullName -HiddenFromAddressListsEnabled $true -DomainController $strDC
}
}
Function Set-PasswordChange {
Param([string]$dn=$(Throw "You must specify a user's DN"),
[switch]$Deny)
#only run if user distinguishedname was found
[ADSI]$user="LDAP://" + $strDC + "." + $strADDomainName + ":389/" + $dn
[Guid]$guid="ab721a53-1e2f-11d0-9819-00aa0040529b"
$everyone = [System.Security.Principal.SecurityIdentifier]"S-1-1-0"
$self = [System.Security.Principal.SecurityIdentifier]"S-1-5-10"
$EveryoneDeny = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($Everyone,"ExtendedRight","Deny",$guid)
$EveryoneAllow = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($Everyone,"ExtendedRight","Allow",$guid)
$SelfDeny = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($self,'ExtendedRight','Deny',$guid)
$SelfAllow = New-Object System.DirectoryServices.ActiveDirectoryAccessRule ($self,'ExtendedRight','Allow',$guid)#Pick the right rules depending on whether $perm is set to Allow or Deny
if ($Deny) {
$SelfRule = $SelfDeny
$EveryoneRule = $EveryoneDeny
}
else
{
$SelfRule = $SelfAllow
$EveryoneRule = $EveryoneAllow
}#The ModifyAccessRuleMethod requires an object to use for its output
New-Variable r
if (!($User.psbase.ObjectSecurity.ModifyAccessRule('Reset',$SelfRule,[ref]$r))) {
Write-Host "Failed to modify access rule for SELF"
Return
}
If (!($User.psbase.ObjectSecurity.ModifyAccessRule('Reset',$EveryoneRule,[ref]$r))) {
Write-Host "Failed to modify access rule for EVERYONE"
Return
}
# changes were made so commit them
$user.psbase.commitchanges()
}
Function Check-ADUser {
#search for user in AD
Param ($Username)
$ADRoot = [ADSI]''
$ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot)
$SAMAccountName = "$Username"
$ADSearch.Filter = "(&(objectClass=user)(sAMAccountName=$SAMAccountName))"
$Result = $ADSearch.FindAll()
If($Result.Count -eq 0)
{
#Write-Host "No such user on the Server" | Out-Null
$Status = "0"
}
Else
{
#Write-Host "User exist on the Server" | Out-Null
$Status = "1"
}
$Results = New-Object Psobject
$Results | Add-Member Noteproperty Status $Status
Write-Output $Results
}
####################################################################
# MAIN SCRIPT #
####################################################################
#Open COM object, start Excel, open Excel File with workbook
$objExcel = New-Object -Comobject Excel.Application
$objExcel.Visible = $True
$objExcelWorkbook = $objExcel.Workbooks.Open($strExcelFile)#First Row contains header, so start with row 2
$objExcelCurrentRow = 2#Loop through excel file and add users with specific settings
do
{
$strADUserLastName = $objExcel.Cells.Item($objExcelCurrentRow,1).Value()
$strADUserMiddleName = $objExcel.Cells.Item($objExcelCurrentRow,2).Value()
$strADUserFirstName = $objExcel.Cells.Item($objExcelCurrentRow,3).Value()
#convert System.double to string value (needed because studentname ia a number)
[string] $strADUserAlias = $objExcel.Cells.Item($objExcelCurrentRow,4).Value()
$strADUserClass = $objExcel.Cells.Item($objExcelCurrentRow,5).Value()
$strADUserSector = $objExcel.Cells.Item($objExcelCurrentRow,6).Value()
$strADUserPassword = $objExcel.Cells.Item($objExcelCurrentRow,7).Value()
If ($strADUserMiddleName -eq $Null) {$strADUserFullName = $strADUserLastName + ", " + $strADUserFirstName} Else {$strADUserFullName = $strADUserLastName + ", " + $strADUserMiddleName + ", " + $strADUserFirstName}
$strADUserDiscription = $strADUserSector + " Class " + $strADUserClass + " (" + $strADUserFullName + ")"
$strADUserPrincipalName = $strADUserAlias + "@" + $strADDomainName
$strADUserEmailAddress = $strADUserAlias + $strExchangeSMTP
$strADUserInitials = $strADUserAlias
$CN = "CN=" + $strADUserAlias
If ($strADUserSector -eq "HVWO") {addHVWOuser}
If ($strADUserSector -eq "PRO") {addPROuser}
If ($strADUserSector -eq "VMBO") {addVMBOuser}
$objExcelCurrentRow++
}
until ($strADUserLastName -eq $Null)#Close Excel Workbook and Excel and cleanup with .Net Framework
$objExcelWorkbook.Close()
$objExcel.Quit()
$Null = & {
[Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)
[Runtime.Interopservices.Marshal]::ReleaseComObject($objExcelWorkbook)
}GC]::Collect()
####################################################################
# END MAIN SCRIPT #
####################################################################
I think this code can easily be followed. If any questions arise or if you have usefull additions or comments don’t hesitate to comment.
The piece that should set the password never expires doesn’t work I changed it to this:
$currentUAC = [int]($newUser.userAccountCOntrol.ToString())
$newUAC = $currentUAC -bor 65536
$newUser.put(“userAccountControl”,$newUAC)
$newUser.SetInfo()
THX for the feedback Danny.
Do you have an example of the spreadsheet you used?
Check your mail.
Can you please send me the spreadsheet example?
CYM
I would love to see a copy of that spreadsheet as well if I could. Thanks.
CYM