Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Import-Module activedirectory
- $MasterFile
- $DomainController = (Get-ADDomain).DNSRoot
- $companyUsersOU = (Get-ADDomain).DistinguishedName
- $UserPath = "OU=Dev," + $companyUsersOU
- $MasterFile = "C:\csv\export7.csv"
- $CSVADMismatch = "C:\csv\mismatch.csv"
- "Reading File"
- $CSV = Import-Csv $MasterFile
- "File Read"
- $ADuserMatch = @()
- $CSVuserMatch = @()
- $CSVMatch = @()
- $NoMatch = ""
- $ADMatch = @()
- $NoDupCSV = @()
- $CSVDUPmsg = ""
- $MisMatch = @()
- $ADDupsBody = ""
- $ADerror = ""
- $i = 0
- $ic = 0
- $it = 0
- $AdModifications = ""
- $Body = ""
- $EID = ""
- $Actions = ""
- $ADMANID = ""
- $CSVMANID = ""
- $PhoneMisMatch = ""
- $ShouldDisable = ""
- $DupCount = 0
- $ADChangeMade = 0
- $ManError = 0
- $Failed = 0
- $ADCreated = 0
- #########################################SMTP Settings##################################
- $From = "test@ctnetworks.net"
- $To = "ryan@ctnetworks.net"
- $Cc = "rgoldstein@itsavvy.com"
- #$Attachment = "C:\temp\Some random file.txt"
- $Subject = "Email Subject"
- $SMTPServer = "10.247.232.12"
- $SMTPPort = "25"
- ######################################################################
- #Find and Remove Duplicates from CSV
- "Creating Dup List"
- $DupList = $CSV | Group-Object -Property "Empl ID" | Where-Object { $_.Count -ge 2 } | ForEach-Object { $_.Group } #Group Hashtable by EmployeeID
- "DUPLIST Created"
- if (($DupList.Count -ge 2) -and ($DupList -ne "")) {
- foreach ($Dup in $DupList) {
- $ic++
- Write-Progress -Activity "Checking Users" -Status "User: $ic of $($DupList.Count)" -PercentComplete (($ic / ($DupList.Count)) * 100)
- $CSVDUPmsg += "THE FOLLOWING DUPLICATE HAS BEEN FOUND PLEASE CHECK THIS USER MANUALLY " + $Dup.("First Name") + " " + $Dup.("Last Name") + ", with employee ID " + $Dup.("Empl ID") + "`r`n" #duplicate users are enumurated into Body
- }
- "creating no DUP CSV"
- $NoDupCSV = $CSV | Group-Object -Property "Empl ID" | Where-Object { $_.Count -le 1 } | ForEach-Object { $_.Group } #New CSV is created
- "NO DUP CSV Created"
- $body += "`r`n`r`n`r`n"
- } else { $NoDupCSV = $csv } #if no dupes are found, hashtable is direct copied
- ############################
- foreach ($User in $NoDupCSV) { #MAIN LOOP checks all users in CSV
- $i++
- Write-Progress -Activity "Checking Users" -Status "User: $i of $($NoDupCSV.Count)" -PercentComplete (($i / ($NodupCSV.Count + 1)) * 100)
- ################################Clears temp variables##########################################
- if ($fname) { Remove-Variable fname } #clears firstname
- if ($lname) { Remove-Variable lname } #clears lastname
- if ($mname) { Remove-Variable mname } #clears lastname
- if ($EID) { Remove-Variable EID } #cleras employeeID
- if ($ADManID) { Remove-Variable ADmanID } #clears ManagerID if it exists (not all users have manager and red errors are annoying)
- if ($CSVman) { Remove-Variable CSVman }
- if ($CSVmanID) { Remove-Variable CSVmanID }
- if ($Action) { Remove-Variable Action }
- if ($DupSAM) { Remove-Variable DupSAM }
- if ($DupUPN) { Remove-Variable DupUPN }
- if ($NewSAM) { Remove-Variable NewSAM }
- if ($NewUPN) { Remove-Variable NewUPN }
- if ($DupDN) { Remove-Variable DupDN }
- if ($NewDN) { Remove-Variable NewDisplayName }
- if ($FriendlyDN) { Remove-Variable FriendlyDN }
- if ($Current) { Remove-Variable Current }
- if ($DupEmail) { Remove-Variable DupEmail }
- ############################################################################################################
- #######SETS BASIC Variables#################
- $fname = $User.("First Name")
- $lname = $User.("Last Name")
- $EID = $User.("Empl ID")
- $Action = $User.("Action")
- ###########################################
- $Current = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(EmployeeID -eq $EID)' #### Searches AD for EMployeeID match #######
- $SamName = $Current.samAccountName
- if ($Current) { #If AD match is found
- ###If 2 AD results are matched Enumerate AD duplicates into body########
- if ($Current.Count -ge 2) {
- #Duplicate Found in AD
- foreach ($ADdup in $Current) {
- $AllADdup = Get-ADUser -Identity $ADdup.samAccountName -PR *
- $ADDupsBody += "THE FOLLOWING DUPLICATE HAS BEEN FOUND IN ACTIVE Directory PLEASE CHECK THIS USER MANUALLY " + $ADDup.givenname + " " + $ADdup.surname + ", with Homepage ID " + $AllADDup.HomePage + " and EmployeeID " + $AllADdup.EmployeeID + "`r`n"
- }
- }
- ##################################################################
- elseif ($Current.Enabled -eq "True") { #Single Match with Enabled ADAccount is found.
- $AllAtrrib = Get-ADUser -Identity $SamName -PR *
- if ($AllAtrrib.Manager) { $ADManID = (Get-ADUser $AllAtrrib.Manager -PR "EmployeeID").EmployeeID } #Retreive Managers Employee ID if manager field is not NULL
- # $ADManID
- if ($mobile) { Remove-Variable mobile }
- $mobile = $AllAtrrib | Select-Object mobilephone
- $ADMatch = New-Object PSObject -Property @{
- "Last Name" = $AllAtrrib.surname
- "First Name" = $AllAtrrib.givenname
- "Company" = $AllAtrrib.Company
- "Department" = $AllAtrrib.Department
- "Title" = $AllAtrrib.Title
- "EmployeeID" = $AllAtrrib.EmployeeID
- "WebsiteID" = $AllAtrrib.HomePage
- "HireDate" = $AllAtrrib.HireDate
- "JobEntryDate" = $AllAtrrib.JobEntryDate
- "ManagerID" = $ADManID
- "Birthdate" = $AllAtrrib.Birthdate
- "MobilePhone" = $Mobile.MobilePhone
- "Location" = $AllAtrrib.Office
- "personalEmail" = $AllAtrrib.personalEmail
- "PSIndex" = $i
- }
- $ADuserMatch += $ADMatch
- $CSVMatch = New-Object PSObject -Property @{
- "Last Name" = $User.("Last Name")
- "First Name" = $User.("First Name")
- "Company" = $User.("Company")
- "Department" = $User.("Department")
- "Title" = $User.("Job Title ")
- "EmployeeID" = $User.("Empl ID")
- "WebsiteID" = $User.("Empl ID")
- "HireDate" = $User.("Hire Date")
- "JobEntryDate" = $User.("Job Entry")
- "ManagerID" = $User.("Reports To Manager ID ")
- "Birthdate" = $User.("Birthdate")
- "MobilePhone" = $User.("Phone Number")
- "Location" = $User.("Location ")
- "personalEmail" = $User.("Electronic Mail Address ")
- "PSIndex" = $i
- }
- $CSVuserMatch += $CSVMatch
- $CompanyMisMatch = Compare-Object $ADMatch $CSVMatch -Property Company | Where-Object { $_.SideIndicator –eq "=>" }
- $DeptMisMatch = Compare-Object $ADMatch $CSVMatch -Property Department | Where-Object { $_.SideIndicator –eq "=>" }
- $TitleMisMatch = Compare-Object $ADMatch $CSVMatch -Property Title | Where-Object { $_.SideIndicator –eq "=>" }
- $JobDateMisMatch = Compare-Object $ADMatch $CSVMatch -Property JobEntryDate | Where-Object { $_.SideIndicator –eq "=>" }
- $HireDateMisMatch = Compare-Object $ADMatch $CSVMatch -Property HireDate | Where-Object { $_.SideIndicator –eq "=>" }
- $IDMisMatch = Compare-Object $ADMatch $CSVMatch -Property EmployeeID | Where-Object { $_.SideIndicator –eq "=>" }
- $WebIDMisMatch = Compare-Object $ADMatch $CSVMatch -Property WebSiteID | Where-Object { $_.SideIndicator –eq "=>" }
- $ManIDMisMatch = Compare-Object $ADMatch $CSVMatch -Property ManagerID | Where-Object { $_.SideIndicator –eq "=>" }
- $BirthMisMatch = Compare-Object $ADMatch $CSVMatch -Property Birthdate | Where-Object { $_.SideIndicator –eq "=>" }
- $MobilePhoneMisMatch = Compare-Object $ADMatch $CSVMatch -Property MobilePhone | Where-Object { $_.SideIndicator –eq "=>" }
- $LocationMisMatch = Compare-Object $ADMatch $CSVMatch -Property Location | Where-Object { $_.SideIndicator –eq "=>" }
- $EmailMisMatch = Compare-Object $ADMatch $CSVMatch -Property personalEmail | Where-Object { $_.SideIndicator –eq "=>" }
- ##################Gets Dates for comparison##############################
- $today = Get-Date
- $JBEntryDate = Get-Date $User.("Job Entry")
- $Hiredate = Get-Date $User.("Hire Date")
- $HiredateDifference = New-TimeSpan $hiredate $today
- #########################################################################
- #$today -ge $JBEntrydate
- if (($User.("Employee Status") -ne "D") -and ($User.("Employee Status") -ne "R") -and ($User.("Employee Status") -ne "T")) {
- ##CREATE EMAIL BODY##
- if ($TitleMisMatch.SideIndicator -eq "=>") { #Changes Jobtitle is JobEntryDate is past.
- if ($today -ge $JBEntrydate) {
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Job Title is being changed to " + $User.("Job Title ") + "`r`n"
- Set-ADUser -Identity $SamName -Title $User.("Job Title ")
- $ADChangeMade = 1
- }
- }
- if ($DeptMisMatch.SideIndicator -eq "=>") { #Changes Department is JobEntryDate is past.
- if ($today -ge $JBEntrydate) {
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Department is being changed to " + $User.("Department") + "`r`n"
- Set-ADUser -Identity $SamName -Department $User.("Department")
- $ADChangeMade = 1
- }
- }
- if ($CompanyMisMatch.SideIndicator -eq "=>") { #Changes Company is JobEntryDate is past.
- if ($today -ge $JBEntrydate) {
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Company is being changed to " + $User.("Company") + "`r`n"
- Set-ADUser -Identity $SamName -Company $User.("Company")
- $ADChangeMade = 1
- }
- }
- if ($LocationMisMatch.SideIndicator -eq "=>") { #sets office locations
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Office Location is being changed to " + $User.("Location ") + " `r`n"
- Set-ADUser -Identity $SamName -Office $User.("Location ")
- $ADChangeMade = 1
- }
- if ($IDMisMatch.SideIndicator -eq "=>") { #SEts EmployeeID Probably never runs
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s EmployeeID is being changed to " + $User.("Empl ID") + "`r`n"
- Set-ADUser -Identity $SamName -EmployeeID $User.("Empl ID")
- $ADChangeMade = 1
- }
- if ($BirthMisMatch.SideIndicator -eq "=>") { #checks birthday
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Birthday is being changed to " + $User.("Birthdate") + "`r`n"
- Set-ADUser -Identity $SamName -Replace @{ Birthdate = $User.("Birthdate") }
- $ADChangeMade = 1
- }
- if ($WEBIDMisMatch.SideIndicator -eq "=>") { #sets Webiste ID
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s WebsiteID is being changed to " + $User.("Empl ID") + "`r`n"
- Set-ADUser -Identity $SamName -HomePage $User.("Empl ID")
- $ADChangeMade = 1
- }
- if ($EmailMisMatch.SideIndicator -eq "=>") { #sets personal email
- if ($User.("Electronic Mail Address ") -and ($User."Electronic Mail Address " -ne " ")) {
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Personal Email is being changed to " + $User.("Electronic Mail Address ") + "`r`n"
- try { Set-ADUser -Identity $SamName -Replace @{ personalEmail = $User.("Electronic Mail Address ") } } catch {}
- $ADChangeMade = 1 }
- }
- if ($HireDateMisMatch.SideIndicator -eq "=>") {
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Hire Date is being changed to " + $User.("Hire Date") + "`r`n"
- Set-ADUser -Identity $SamName -Replace @{ HireDate = $User.("Hire Date") }
- $ADChangeMade = 1
- }
- if ($JobDateMisMatch.SideIndicator -eq "=>") {
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Job Entry Date is being changed to " + $User.("Job Entry") + "`r`n"
- Set-ADUser -Identity $SamName -Replace @{ JobEntryDate = $User.("Job Entry") }
- $ADChangeMade = 1
- }
- if ($MobilePhoneMisMatch.SideIndicator -eq "=>") {
- if (($User."Phone Number") -and ($User."Phone Number" -ne " ")) {
- $AdModifications += $User.("First Name") + " " + $User.("Last Name") + "'s Mobile Phone is being changed to " + $User.("Phone Number") + "`r`n"
- Set-ADUser -Identity $SamName -MobilePhone $User.("Phone Number") }
- $ADChangeMade = 1
- }
- if ($ManIDMisMatch.SideIndicator -eq "=>") {
- if (($User.("Reports To Manager ID ")) -and ($User.("Reports To Manager ID ")) -ne " ") {
- $Body += $User.("First Name") + " " + $User.("Last Name") + "'s Manager ID " + $User.("Reports To Manager ID ") + " Does not Match AD `r`n"
- $CSVMANID = $User.("Reports To Manager ID ")
- $CSVMan = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(EmployeeID -eq $CSVMANID)'
- if ($csvman) {
- Set-ADUser -Identity $SamName -Manager $CSVMan
- $ADChangeMade = 1
- }
- if ($csvman) { $AdModifications += "Manager is being set to " + $CSVMan + "`r`n" }
- else {
- $Body += "Manager ID from CSV could not be found in AD" + "`r`n"
- $ManError = 1
- $Body += "`r`n"
- }
- }
- }
- $AdModifications += "`r`n"
- }
- elseif ($AllAtrrib.Enabled -eq "True") { $ShouldDisable += $User.("First Name") + " " + $User.("Last Name") + " with EmployeeID " + $User.("Empl ID") + " Should be Disabled! `r`n" }
- }
- } else { #If their is NOT a AD match
- #######################################If EmployeeID does not match Does not Exist################################################################
- if (($User.("Employee Status") -ne "D") -and ($User.("Employee Status") -ne "R") -and ($User.("Employee Status") -ne "T")) {
- $fname = $User.("First Name") -replace '[-]',"" -replace '[.]',"" -replace '[,]',""
- $lname = $User.("Last Name") -replace '[-]',"" -replace '[.]',"" -replace '[,]',""
- $mname = $user.("Middle Name").Substring(0,1) -replace '[-]',"" -replace '[.]',"" -replace '[,]',""
- #################################Random Password Generator########################################
- $assembly = Add-Type -AssemblyName System.Web
- $password = [System.Web.Security.Membership]::GeneratePassword(10,2)
- ###################################################################################################
- ############################################Set Variables for New User#########################################
- $CSVMANID = $User.("Reports To Manager ID ")
- $CSVMan = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(EmployeeID -eq $CSVMANID)'
- $NewSam = $fname.ToLower() + "." + $lname.ToLower()
- if ($NewSAM.length -gt 19) { $NewSAM = $NewSAM.Substring(0,19) }
- $NewDisplayName = ($User.("First Name") + " " + $User.("Last Name")) -replace '[-]'," " -replace '[.]'," "
- $FriendlyDN = ($User.("First Name") + " " + $User.("Last Name")) -replace '[-]'," " -replace '[.]'," "
- $NewUPN = ($NewSam + "@" + $DomainController).Trim()
- $setpass = ConvertTo-SecureString -AsPlainText ("$password") -Force
- $newSam = $NewSAM -replace '\s',''
- ########################################################################################################################
- #############################################Check for Dup UPN or SAM #################
- $DupSAM = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(SamAccountName -eq $NewSam)'
- $DupEmail = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(EmailAddress -eq $NewUPN)'
- #################################################################################################################
- if (($DupSAM -or $DupEmail)) {
- $NewSam = $fname.ToLower() + $mname.ToLower() + "." + $lname.ToLower()
- if ($NewSAM.length -gt 19) { $NewSAM = $NewSAM.Substring(0,19) }
- $newSam = $NewSAM -replace '\s',''
- $NewUPN = ($NewSam + "@" + $DomainController).Trim()
- }
- $DupSAM = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(SamAccountName -eq $NewSam)'
- $DupEmail = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(EmailAddress -eq $NewUPN)'
- while (($DupSAM -or $DupEmail)) {
- $DupCount++
- $NewSam + " Is a DUP"
- $NewSAM = $fname.ToLower() + "." + $lname.ToLower() + $DupCount
- if ($NewSAM.length -gt 19) { $NewSAM = $NewSAM.Substring(0,19) }
- $newSam = $NewSAM -replace '\s',''
- $DupSAM = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(SamAccountName -eq $NewSam)'
- $NewUPN
- $NewUPN = ($NewSam + "@" + $DomainController).Trim()
- $DupEmail = Get-ADUser -SearchBase $companyUsersOU -Server $DomainController -Filter '(EmailAddress -eq $NewUPN)'
- }
- $newSam = $NewSAM -replace '\s',''
- $NewUPN = ($NewSam + "@" + $DomainController).Trim()
- $DupCount = 1
- ##############################################################################################################
- ############################################Checks for duplicate CN########################################################
- $DupDN = Get-ADUser -SearchBase $userpath -Server $DomainController -Filter '(CN -eq $NewDisplayName)'
- if ($DupDN) { $NewDisplayName = ($User.("First Name") + " " + $user.("Middle Name") + " " + $User.("Last Name")) -replace '[-]'," " -replace '[.]'," " }
- $DupDN = Get-ADUser -SearchBase $userpath -Server $DomainController -Filter '(CN -eq $NewDisplayName)'
- while (($DupDN) -or ($DupCount > 20)) {
- $NewDisplayName = ($User.("First Name") + " " + $User.("Last Name") + " " + $DupCount) -replace '[-]'," " -replace '[.]'," "
- $DupCount++
- $DupDN = Get-ADUser -SearchBase $userpath -Server $DomainController -Filter '(CN -eq $NewDisplayName)'
- }
- #########################################################################################################################
- #########################################Creating AD account##################################################
- if ($HiredateDifference.Days -lt 8) {
- $ADCreated = 1
- try { New-ADUser $NewDisplayName -SamAccountName $NewSam -DisplayName $FriendlyDN -GivenName $User.("First Name") -Surname $User.("Last Name") `
- -UserPrincipalName $NewUPN -Company ($User.("Company")) -Department $User.("Department") `
- -Title $User.("Job Title ") -EmployeeID $User.("Empl ID") -MobilePhone $User.("Phone Number") -HomePage $User.("Empl ID") `
- -Manager $CSVMan -Office $User.("Location ") -AccountPassword $setpass -Enabled $True -Path $UserPath `
- -OtherAttributes @{ 'HireDate' = $User.("Hire Date"); 'JobEntryDate' = $User.("Job Entry"); 'birthdate' = $User.("Birthdate") } }
- catch {
- #"NO AD FOR YOU"
- $_
- $ADerror += $fname + " " + $lname + " generated an error when trying to create an AD account "
- $Failed = 1
- }
- try { Set-ADUser -Identity $newsam -Replace @{ personalEmail = $User.("Electronic Mail Address ") } } catch {}
- #$NewDisplayName + "is not valid with samName" +$NewSAM + " user ID " + $User.("Empl ID")
- ################################################################################################################################
- ##############################################Send Email to manager################################
- $NewEmployee = "Hello " + $CSVman.givenname + " " + $CSVman.surname + "`r`n`r`n" + `
- "A new Employee " + $User.("First Name") + " " + $User.("Last Name") + ", with the EmployeeID " + $User.("Empl ID") + " has been Created" + "`r`n`r`n" + `
- "The username is " + $NewSAM + " with a password of " + $password + "`r`n`r`n" + `
- "Click here for permissions and fill out the following form" + "`r`n`r`n" + `
- "Click here if you feel this email is created in error"
- $NoMatch += "An AD Account is being created for " + $User.("First Name") + " " + $User.("Last Name") + " with the EmployeeID " + $User.("Empl ID")
- $NoMatch += "`r`n"
- if ($failed = 0) {
- Send-MailMessage -From $From -To $To -Subject $Subject `
- -Body $NewEmployee -SmtpServer $SMTPServer -Port $SMTPPort `
- #-Credential (Get-Credential) #-Attachments $Attachment
- }
- }
- ################################################################################################################
- }
- }
- }
- $ADuserMatch | Export-Csv C:\csv\ADMatches.csv -NoTypeInformation
- $CSVuserMatch | Export-Csv C:\csv\CSVMatches.csv -NoTypeInformation
- #$NoMatch | Export-Csv C:\csv\NoMatches.csv -NoTypeInformation
- #$MisMatch |
- #Select-Object "Last Name","First Name","ADCompany","CSVCompany","ADDepartment","CSVDepartment","ADTitle","CSVTitle" |
- #Export-Csv C:\csv\MixMatches.csv -NoTypeInformation
- $body += $CSVDUPmsg
- $body += "`r`n"
- $body += $ADDupsBody
- $body += $PhoneMisMatch
- $Body += "`r`n"
- $Body += $ShouldDisable
- #$body += $NoMatch
- $SaveTime = (Get-Date).ToString("yyyy-MM-dd__hh-mm")
- if($ManError -eq 1){
- $SavePath = "C:\Scripts\Logs\ADMODErrors_" + $SaveTime + ".txt"
- $body | Out-File $SavePath
- }
- if($failed -eq 0){
- $SavePath = "C:\Scripts\Logs\ADAccounts_Created_" + $SaveTime + ".txt"
- $NoMatch | Out-File $SavePath
- }
- If($ADChangeMade -eq 1){
- $SavePath = "C:\Scripts\Logs\ADchangesMade_" + $SaveTime + ".txt"
- $AdModifications | Out-File $SavePath
- }
- if ($ADcreated -eq 1) {
- $SavePath = "C:\Scripts\Logs\ADCreation_error_" + $SaveTime + ".txt"
- $ADerror | Out-File $SavePath
- }
Add Comment
Please, Sign In to add comment