Advertisement
JustinCooper

Aeries to AD

Nov 13th, 2013
379
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. Updated 2013-11-13 2:27PM Pacific - Justin Cooper
  3.  .Synopsis
  4.     Active Directory student account and home directory modification and creation.
  5.  .DESCRIPTION
  6.     This script queries and SQL DB and created Student Active Directory User accounts and home directories from the results.
  7.  .EXAMPLE
  8.     Example of how to use this workflow
  9.  .EXAMPLE
  10.     Another example of how to use this workflow
  11.  .INPUTS
  12.     When Automating this script as a scheduled task please keep input files in the same directory as the script itself.
  13.     Mandatory and in order on the powershell command line:
  14.     Aeries SQL Server
  15.     Aeries SQL DB
  16.     Aeries Read-Only DB Account
  17.     Aeries DB account password
  18.     SQL txt-based query file
  19.     LookUpTable txt/csv file
  20.     LogFile to output results, INFO, and possible ERROR
  21.  .OUTPUTS
  22.     Student Active Directory User accounts and home directories are created.
  23.  .NOTES
  24.     Needs AD ADmin tools locally installed or run on a DC with PowerShell v2+
  25.     Please keep associated files in the scripts root dir
  26.     The account running the script must have permissions to:
  27.         -Add/Move AD UserObjects
  28.         -Modify Groups Memberships on AD Group Objects
  29.         -Create folders and set permissions on target Home folders.
  30.         -Write access to the log file
  31.  THe site lookup CSV file's columns headers are formatted as such:
  32. SiteCode|SiteName|StudentOU|StaffSecurityGroup|StudentSecurityGroup|StudentHomeDir|8e6SecurityGroup
  33.  .FUNCTIONALITY
  34.    
  35.  #>
  36. Param( 
  37.     [Parameter(Mandatory=$True)][ValidateNotNull()][STRING]$SCRIPT:AeriesServer,
  38.     [Parameter(Mandatory=$True)][ValidateNotNull()][STRING]$SCRIPT:AeriesDB,
  39.     [Parameter(Mandatory=$True)][ValidateNotNull()][STRING]$SCRIPT:AeriesDBAccount,
  40.     [Parameter(Mandatory=$True)][ValidateNotNull()][STRING]$SCRIPT:AeriesPassword,
  41.     [Parameter(Mandatory=$True)][ValidateNotNull()][String]$SCRIPT:sqlFile,
  42.     [Parameter(Mandatory=$True)][ValidateNotNull()][STRING]$SCRIPT:ltTableFile,
  43.     [Parameter(Mandatory=$True)][ValidateNotNull()][STRING]$SCRIPT:logFile
  44. )
  45. CLS
  46. #Begin Checking Snappins and modules
  47.     IF ( !(Get-Module -ListAvailable | where {$_.Name -eq 'ActiveDirectory'}) )
  48.     {
  49.         Write-Host "Active Directory Tools not installed on $ENV:COMPUTERNAME`nScript Terminating" -ForeGroundColor Red
  50.         Add-Content $logFile -value "$(Get-Date) [ERROR] Active Directory Tools not installed on $ENV:COMPUTERNAME`nScript Terminating"
  51.     }
  52.     ELSEIF ( !(Get-Module -Name ActiveDirectory) )
  53.     {
  54.         Import-Module ActiveDirectory
  55.     }
  56. #End Checking Snappins and modules
  57. #Setting Script's Working Directory
  58.     $cwd = Split-Path $MyInvocation.MyCommand.Path
  59.     CD $cwd
  60.     #sleep 30
  61. #script variables
  62.     $lookUpTable = Import-Csv $ltTableFile -Delimiter "|"
  63.     $Query = Get-Content $sqlFile
  64. #script functions
  65.     function Add-HomeDirectory
  66.     {
  67.         Param(
  68.             [String]$f_homeRoot,
  69.             [String]$f_homeDir,
  70.             [String]$f_samid,
  71.             [String]$f_StaffSecurityGroup
  72.         )
  73.         #Create Home Directory
  74.         $homeTest = Test-Path $f_homeDir
  75.         IF ( $homeTest -ne $True ) {
  76.             Write-Host "Creating Directory" -ForegroundColor DarkGreen
  77.             MD $f_homeRoot
  78.             MD $f_homeDir
  79.             #Set Homedir ACL's
  80.             ICACLS $f_homeRoot /inheritance:r /grant "Domain Admins:(OI)(CI)(F)" "${f_StaffSecurityGroup}:(OI)(CI)(M)" "${f_samid}:(OI)(CI)(RX)"
  81.             ICACLS $f_homeDir /inheritance:r /grant "Domain Admins:(OI)(CI)(F)" "${f_StaffSecurityGroup}:(OI)(CI)(M)" "${f_samid}:(OI)(CI)(M)"
  82.             #Log Home Directory Creation
  83.             Add-Content $logFile -value "$(Get-Date) [INFO] $homeDir created"
  84.         }
  85.         ELSE {
  86.             Write-Host "Directory $homeDir already exists." -ForegroundColor Green
  87.         }
  88.     }
  89.     function Add-UsertoADGroups
  90.     {
  91.         Param(
  92.             [String]$f_samid,
  93.             [String]$f_group1,
  94.             [String]$f_group2
  95.         )
  96.         Write-Host "Setting Groups..."-ForegroundColor Green
  97.         Add-ADGroupMember -Identity $f_group1 -Members $f_samid
  98.         Add-ADGroupMember -Identity $f_group2 -Members $f_samid
  99.     }
  100.     function Set-DefaultPassword
  101.     {
  102.         param(
  103.             [STRING]$f_samid,
  104.             $f_ID
  105.         )
  106.         Write-Host "Setting Default Password..." -ForeGroundColor Yellow
  107.         Set-ADAccountPassword $f_samid -NewPassword (ConvertTo-SecureString $f_ID -AsPlainText -force) -Reset
  108.     }
  109.  
  110. #Connect and Query Aeries Database and set results to an PS object "$dbResults"
  111.     $ServerInstance = "$AeriesServer "
  112.     $Database = "$AeriesDB "
  113.     $ConnectionTimeout = 30
  114.     $QueryTimeout = 120
  115.     $conn=new-object System.Data.SqlClient.SQLConnection
  116.     $ConnectionString = "Server={0};Database={1};Connect Timeout={2};User Id = $AeriesDBAccount; Password = $AeriesPassword" -f $ServerInstance,$Database,$ConnectionTimeout
  117.     $conn.ConnectionString=$ConnectionString
  118.     $conn.Open()
  119.     $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn)
  120.     $cmd.CommandTimeout=$QueryTimeout
  121.     $ds=New-Object system.Data.DataSet
  122.     $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
  123.     [void]$da.fill($ds)
  124.     $conn.Close()
  125.     $dbResults = $ds.Tables.Rows | Select-Object -Property ln,fn,id,sc,ed
  126. #Set Counter
  127.     $i = $dbResults | measure | select -Property count
  128.     $i = $i.count
  129.  
  130. #Log Begin
  131.     Add-Content $logFile -value "`nScript Begin - $(Get-Date) `nRunning as:$ENV:USERNAME`nScript Parameters: $AeriesServer $AeriesDB $AeriesDBAccount DBPASSWORDEXCLUDED $sqlFile $ltTableFile $logFile"
  132.  
  133. #Begin Parse Database Query Results
  134. ForEach ( $dbRow in $dbResults )
  135. {
  136.     CLS
  137.     #Set User Related Variables
  138.     $FN = $dbRow.FN
  139.     $LN = $dbRow.LN
  140.     $ID = $dbRow.ID
  141.     $SC = $dbRow.SC
  142.     $ED = $dbRow.ED
  143.     $samid = $FN.substring(0,1)+$LN.substring(0,1)+$ID
  144.     $email = $samid+"@chicousd.net"
  145.     $date = Get-Date
  146.     Write-host `n $i $samid `n -ForegroundColor Yellow
  147.     $i--
  148.     #Begin Check Site Code
  149.     ForEach ( $dbRow2 in $dbResults )
  150.     {
  151.         #Older and non-matching results are filter out here
  152.         IF ( ($dbRow.ID -eq $dbRow2.ID) -and ($dbRow.ED -ge $dbRow2.ED) )
  153.         {
  154.             #Begin Parse LookUpTable
  155.             ForEach ( $ltRow in $lookUpTable )
  156.             {
  157.                 #Compare LookUpTable SiteCode to Aeries Result SiteCode
  158.                 IF ( $ltRow.SiteCode -eq $dbRow.SC )
  159.                 {
  160.                     #Set table-related variables
  161.                     $desc = $ltRow.SiteName+" Student"
  162.                     $OU =  $ltRow.StudentOU
  163.                     $homeRoot = $ltRow.StudentHomeDir+'\'+$samid
  164.                     $homeDir = $ltRow.StudentHomeDir+'\'+$samid+"\Documents"
  165.                     $StaffSecurityGroup = $ltRow.StaffSecurityGroup
  166.                     $studentSecurityGroup = $ltRow.StudentSecurityGroup
  167.                     $8e6SecurityGroup = $ltRow."8e6SecurityGroup"
  168.                 }
  169.             }
  170.             #End Parse LookUpTable
  171.             #Creates object "$userObj" with "memberof" property included
  172.             $userObj = Get-ADUser -LDAPFilter "(sAMAccountName=$samid)" -Properties memberof
  173.             #Check AD for $userObj
  174.             IF ( $userObj -eq $NULL )
  175.             {
  176.                 #Create New User Object
  177.                 Write-Host "Creating User Account..." -ForegroundColor DarkGreen
  178.                 $descNew = $desc + " - Created on " + $date
  179.                 New-ADUser `
  180.                     -Name $samid `
  181.                     -DisplayName $samid `
  182.                     -SamAccountName $samid `
  183.                     -GivenName $FN `
  184.                     -SurName $LN `
  185.                     -UserPrincipalName $samid `
  186.                     -EmailAddress $email `
  187.                     -AccountPassword (ConvertTo-SecureString $ID -AsPlainText -force) `
  188.                     -PasswordNeverExpires $True `
  189.                     -CannotChangePassword $False `
  190.                     -Path $OU `
  191.                     -Enabled $True
  192.                 Set-ADUser $samid -Description $descNew
  193.                 Set-DefaultPassword $samid $ID
  194.                 #BEGIN Security Group(s) modification
  195.                 Add-UsertoADGroups $samid $studentSecurityGroup $8e6SecurityGroup
  196.                 #END Security Group(s) modification
  197.                 #BEGIN Check Object
  198.                 #Maximum wait time for each creation and propagation is 60 seconds.
  199.                 $i2 = 60
  200.                 Write-Host "`nWaiting for $samid UserObject to be created and replicated...`n" -ForegroundColor Yellow
  201.                 DO { Sleep 1; $i2-- }
  202.                 UNTIL ( $i2 -le 0 -or (Get-ADUser -LDAPFilter "(sAMAccountName=$samid)" -searchbase $OU ) )
  203.                 $userObj = Get-ADUser -LDAPFilter "(sAMAccountName=$samid)" -Properties memberof
  204.                 #If something goes really wrong the script ends and outputs an error to the log file.
  205.                 IF ( $userObj -eq $NULL )
  206.                 {
  207.                     #WARNING - This is an EXIT to catch errors in AD user object creation and prevent cascading account and folder creation issues.
  208.                     Write-host "User Object not created as expected!`nLogging error." -ForeGRoundColor Red
  209.                     Add-Content $logFile -value "$(Get-Date) [ERROR] Object not created,$samid"
  210.                     Add-Content $logFile -value "$(Get-Date) [FATAL ERROR] Script Process Terminating"
  211.                     EXIT
  212.                 }
  213.                 #End Check Object
  214.                 ELSE {
  215.                     #Display and log successful AD user object creation
  216.                     Write-host "`nUser Object created!" -ForeGRoundColor DarkGreen
  217.                     Add-Content $logFile -value "$(Get-Date) [INFO] $samid created - $desc"
  218.                 }
  219.             }
  220.             ELSEIF ( $userObj.DistinguishedName -notlike "*$OU*" )
  221.             {
  222.                 #Move User Object
  223.                 Write-Host "Moving User Account..." -ForegroundColor Magenta
  224.                 $userObj | Move-ADObject -TargetPath $OU
  225.                 Write-Host "Resetting AD LDAP Account Info..." -ForegroundColor Magenta
  226.                 $descMove = $desc + " - Moved on " + $date
  227.                 Set-ADUser `
  228.                     -Identity $samid `
  229.                     -DisplayName $samid `
  230.                     -GivenName $FN `
  231.                     -SurName $LN `
  232.                     -UserPrincipalName $samid
  233.                 Set-ADUser $samid -Description $descMove
  234.                 #Clear Old Groups
  235.                 ForEach ( $groupCN in $userObj.MemberOf )
  236.                 {
  237.                     IF ( $groupCN -notlike "*Domain User*" )
  238.                     {
  239.                         Write-Host "Removing from group..." $groupCN -ForegroundColor Magenta
  240.                         Remove-ADGroupMember -identity (Get-ADGroup -LDAPFilter "(DistinguishedName=$groupCN)" -property Name) -Members $samid -Confirm:$false
  241.                     }
  242.                 }
  243.                 #Security Groups
  244.                 Add-UsertoADGroups $samid $studentSecurityGroup $8e6SecurityGroup
  245.  
  246.                 #Display and log AD user object move
  247.                 Write-host "`nUser Object moved." -ForeGRoundColor DarkGreen
  248.                 Add-Content $logFile -value "$(Get-Date) [INFO] $samid moved to $desc"
  249.  
  250.             }
  251.             #Create HomeDir
  252.             Add-HomeDirectory $homeRoot $homeDir $samid $StaffSecurityGroup
  253.             #SLEEP 1
  254.         }
  255.     }
  256.     #Begin Check Site Code
  257. }
  258. #End Parse Database Query Results
  259. #Log End
  260.     Add-Content $logFile -value "Script End - $(Get-Date)"
  261. CLS
  262. Write-Host "Script Completed - $(Get-Date)`n" -ForeGroundColor Yellow
  263. #Script End
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement