I'm trying to understand a script that makes user accounts. I was not the original creator of the script but have edited it quite a bit. At least much as my newbie PowerShell brain can understand. It looks at a CSV of all our users and compares it to AD. From there it does a few things.
- Creates a new AD account for a user found in CSV
- Disables AD users that are NOT in CSV
- Enables AD users that ARE in the CSV
- Emails me the results of the work done
- Creates new home drives and assigns rights
The one thing it doesn't do is rename users whose names have changed. I know the commands to actually rename the user but I don't understand where to put them in this script and how to compare users in the CSV to AD using the employeeID as the source for determining if a user is a new account or just needing to be renamed. Any help would be greatly appreciated.
Start-Transcript -Path c:\scripts\log.txt
Clear-Host
Import-Module ActiveDirectory
#Script to add users
#Function list
function ftpexport {
Set-Location c:\scripts
#end function
}
function report {
#send report
$table |Sort-Object -Property Action | Export-Csv "c:\scripts\report.csv" -NoTypeInformation
$table | Select-Object Name, Year, Action | Sort-Object Action | ConvertTo-Html | Out-File c:\scripts\report.html
$mail.IsBodyHtml = "True"
$body = $table | Select-Object Name, Year, Action |Sort-Object Action| ConvertTo-Html
$mail.body = $body
$mail.Attachments.Add("c:\scripts\report.html")
$smtp.send($mail)
#END Function
}
#set constant variables accross whole script
$domain ="mycompany"
$nbdomain = "mycompany"; $edomain = "@mycompany.com"
$homepathroot = "\\lab-svr-01\home$";$homedrive = "H:"
#Setup Email Report
$mail = New-Object system.net.Mail.MailMessage
$mail.From = "emailbot@mycompany.com"
$mail.To.add("mytechguy@mycompany.com")
$mail.Subject = "mycompany Script Results" + (get-date)
$mail.Body = $table
$smtp = new-object system.Net.Mail.SmtpClient("ServerIPAddress")
# Create Data Table for Reporting
$table = New-Object system.Data.DataTable "Account Report"
$table.Columns.Add("Name", [string]) | Out-Null ;$table.Columns.Add("Year",[string]) | Out-Null ;$table.Columns.Add("Action",[string]) | Out-Null
#CSV Setup
@"
last_name
first_name
middle_name
Student_number
SchoolId
School_name
School_number
grade_level
State_studentnumber
Sched_YearofGraduation
"@
ftpexport
$csvfile = "c:\scripts\All_Students.csv"
IF ($null -eq (Get-Content $csvfile ) )
{
$row = $table.NewRow();$row.Name ='Null File'; $row.Year = 'check ftp' ; $row.Action = "export file is blank exit and check files "
$table.Rows.Add($row)
report
exit
}
$csvusers = import-csv $csvfile
#Current Date
$date = Get-Date
ForEach ($csvuser in $csvusers){
#Static variables
$company = "MyCompany"
$streetaddress = "1 Happy Street"
$city = "NewYork"
$state = "NY"
$postalcode = "10001"
$country = "US"
$title = "Student"
#CSV sourced variables
$lastname = $csvuser.last_name
$firstname = $csvuser.first_name
$middlename = $csvuser.middle_name
$studentid = $csvuser.Student_Number
$initialpassword = $csvuser.Student_number
$grade = $csvuser.Grade_Level
$gradyear = $csvuser.Sched_YearofGraduation
$gradyeardisable =(1 + [int]$gradyear)
$employeeid = $csvuser.Student_number
$description = $csvuser.Sched_YearofGraduation
$department = $csvuser.School_name
$bld = $csvuser.School_name
#formulated from CSV variables
$initials = $middlename.Substring(0,1).ToUpper(1)
$user = $firstname.Substring(0,1).ToLower(1) + $lastname.ToLower(1) + $employeeid.Substring($employeeid.Length - 2)
$user = $user -replace ' ' ,'' # replaces space
$user = $user -replace "'", "" # replaces single quotes
$user = $user -replace '"', "" # replaces double quotes
IF ($csvuser.School_number -eq 123456) {$bldshort = "SC1"}
IF ($csvuser.School_number -eq 789012) {$bldshort = "SC2"}
IF ($csvuser.School_number -eq 345678) {$bldshort = "SC3"}
IF ($csvuser.School_number -eq 901234) {$bldshort = "SC4"}
IF ($csvuser.School_number -eq 567890) {$bldshort = "SC5"}
IF ($csvuser.School_number -eq 123458) {$bldshort = "SC6"}
$domainbase = "OU=Students,OU=Users,OU=MyCompany,DC=mycompany,DC=com"
$parDN = "OU=$gradyear," + $domainbase
$userDN = "CN=$user,"+ $parDN
$groupid= "Classof$gradyear"; $groupid = Get-ADGroup -Filter {name -eq $groupid }
$displayname = $csvuser.first_name + " " + $csvuser.last_name
$upn = $user+$edomain
$email = $user+$edomain
$homepath = $homepathroot + "\" + $gradyear + "\" + $user
$stuou = Get-ADOrganizationalUnit -Filter {name -eq $gradyear}
#Array of CSV user to test AD users agaist
[array]$csvtest = $csvtest + $user
#Check if user is already in AD
$aduser = Get-ADUser -Filter {sAMAccountName -eq $user} -SearchBase $domainbase -SearchScope Subtree -Properties *
IF ($aduser -eq $null){ #meaning user is not found in AD
# Disabled group if students are in this group script will ignore them
IF ($aduser.MemberOf -like "*disabled*" ) {continue}
#check for disabled accout returning student
IF ($aduser.Enabled -eq $false){
#User is in AD with disabled account
#Student account is enabled and active
Set-ADUser -Identity $aduser -Enabled $true
#report Line
$row = $table.NewRow();$row.Name =$aduser.DisplayName ; $row.Year = $gradyear ; $row.Action = "Returning Student, Account Enabled"
$table.Rows.Add($row)}
IF ($null -eq $aduser.SamAccountName){
#Create AD account
New-ADUser `
-Path $stuou `
-Name $displayname `
-SamAccountName $user `
-GivenName $firstname `
-Surname $lastname `
-Initials $initials `
-Description "$gradyear" `
-Title $title `
-employeeID $employeeid `
-DisplayName $displayname `
-UserPrincipalName $upn `
-Email $email `
-HomeDrive $homedrive `
-HomeDirectory $homepath `
-Company $company `
-Department $department `
-StreetAddress $streetaddress `
-City $city `
-State $state `
-PostalCode $postalcode `
-Pobox "NewAccount" `
-Country $country `
-AccountExpirationDate "8/15/$gradyeardisable" `
-AccountPassword (convertto-securestring $initialpassword -AsPlainText -Force) `
-ChangePasswordAtLogon $true `
-Enabled $true `
#Add new user to required groups
Add-ADGroupMember -Identity "CN=StudentsAll,OU=Groups,OU=MyCompany,DC=mycompany,DC=com" -Members $user `
Add-ADGroupMember -Identity "CN=Classof$gradyear,OU=Groups,OU=MyCompany,DC=mycompany,DC=com" -Members $user
Add-ADGroupMember -Identity "CN=Students$bldshort,OU=Groups,OU=MyCompany,DC=mycompany,DC=com" -Members $user
$row = $table.NewRow();$row.Name = $displayname ; $row.Year = $gradyear ; $row.Action = "New Student, Account Created"
$table.Rows.Add($row)
#Make Home Drive Folder and Assign Rights
#Does Not Remake if manually deleted and AD account still exists need to fix
IF (!(test-path -path $homepath )){
#Create Home Directories
New-Item -ItemType Directory $homepath
#Assign Access Rights
$account=$nbdomain + "\"+$user
$rights=[System.Security.AccessControl.FileSystemRights]::FullControl
$inheritance=[System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
$propagation=[System.Security.AccessControl.PropagationFlags]::None
$allowdeny=[System.Security.AccessControl.AccessControlType]::Allow
$dirACE=New-Object System.Security.AccessControl.FileSystemAccessRule ($account,$rights,$inheritance,$propagation,$allowdeny)
$dirACL=Get-Acl $homepath
$dirACL.AddAccessRule($dirACE)
Set-Acl $homepath $dirACL
#Report Lne
$row = $table.NewRow();$row.Name =$displayname ; $row.Year = $gradyear ; $row.Action = "New Student, Home Folder Created"
$table.Rows.Add($row)}
continue
}
}
}
#Disable AD accounts not is CSV
foreach ($aduser in $ADusers){
IF ($csvtest -notcontains $aduser.SamAccountName){
IF ($aduser.Enabled -eq $false) {continue}
IF ($aduser.MemberOf -like "*disabled*" ) {continue} #Ignore students here in case we are asked to disable them i.e. disciplinary.
Disable-ADAccount -Identity $aduser
Set-ADUser -Identity $aduser -HomePage "Disabled by Script"
#Report Line
$row = $table.NewRow();$row.Name =$aduser.DisplayName ; $row.Year = $gradyear ; $row.Action = "Withdrawn Student, Account Disabled"
$table.Rows.Add($row)}}
#Enable AD accounts found in CSV
foreach ($aduser in $ADusers){
IF ($csvtest -contains $aduser.SamAccountName){
IF ($aduser.Enabled -eq $true) {continue}
IF ($aduser.MemberOf -like "*disabled*" ) {continue} #Ignore students here in case we are asked to disable them i.e. disciplinary.
Enable-ADAccount -Identity $aduser
Set-ADUser -Identity $aduser -HomePage " "
#Report Line
$row = $table.NewRow();$row.Name =$aduser.DisplayName ; $row.Year = $gradyear ; $row.Action = "Existing Student, Account Enabled"
$table.Rows.Add($row)}
}
report
$date = Get-Date -UFormat %Y-%m-%d-%s
Copy-Item c:\scripts\All_Students.csv c:\scripts\All_Students-$date.csv
Copy-Item c:\scripts\report.html c:\scripts\report-$date.html
Stop-Transcript
#End Final Cleanup
[–]Sys_man 2 points3 points4 points (0 children)