smartguy5000

computersOUCleanup.ps1

Jan 6th, 2017
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <#
  2. .SYNOPSIS
  3.     Powershell script to move computers into designated Schools\Employees Sub-OUs
  4. .DESCRIPTION
  5.    Queries the default container, pings host, if online, moves based on IP, if 10.254, goes by dept number.
  6. .PARAMATER
  7. -debug "turns on visible debugging, warning all ye who enter here, your eyes shall bleed"
  8. .EXAMPLE
  9.     .\computersOUCleanUp.ps1
  10. .OUTPUTS
  11. log file, C:\Windows\Temp\Logs\computersOUCleanUp$date.log
  12. .NOTES
  13.     Name: computersOUCleanUp.ps1
  14.     Author: \u\Smartguy5000
  15.     Last Modified: 05/11/2016 10:20
  16. .CHANGELOG
  17. v1.0 Intitial write
  18. v1.1 Improved syntax of some variables. Removed unnecessary functions
  19. v1.2 fixed departmental computers section
  20. .VERSION
  21. 1.2
  22. .LINK
  23. #>
  24. [CmdletBinding()]
  25. Param(
  26. )
  27.  
  28. If ($PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent)
  29.     {
  30.          $DebugPreference="Continue"
  31.          $d = $:true
  32.          If ($d) {Write-Debug "Debug Output activated"}
  33.     }
  34. Else
  35.     {
  36.          $d = $:false
  37.          $DebugPreference="SilentlyContinue"
  38.     }
  39.  
  40. #logging module files have not been sanitized
  41. $moduleFile1 = ""
  42. $moduleFile2 = ""
  43. $moduleFile1content = [System.Convert]::FromBase64String($moduleFile1)
  44. $moduleFile2content = [System.Convert]::FromBase64String($moduleFile2)
  45. $VerbosePreference = "continue"
  46. $tempDate = get-date -Uformat %D
  47. $currentDate = $tempDate -replace "/", "-"
  48. $logname = "$env:windir\Temp\logs\" + "computersOUCleanUp" + $currentDate + ".log"
  49. $ErrorActionPreference = "Stop"
  50.  
  51. Write-Verbose "Variables have been declared"
  52. Write-Verbose "## ----------------------------------------------------------------"
  53. ##----------------------------------------------------------------
  54.  
  55. ## environment setup
  56. Write-Verbose "Setting up environment"
  57. If (!(Test-Path $env:windir\Temp\LogIt))
  58.     {
  59.         If ($d) {Write-Debug "Creating Logging Module folder"}
  60.         New-Item -ItemType Directory -Path $env:windir\Temp\LogIt | Out-Null
  61.     }
  62. If(!(Test-Path $env:windir\Temp\Logs))
  63.     {
  64.         If ($d) {Write-Debug "Creating logs directory"}
  65.         New-Item -ItemType Directory -Path $env:windir\Temp\Logs | Out-Null
  66.     }
  67. Set-Content -Path $env:windir\Temp\LogIt\LogIt.psm1 -Value $moduleFile1content -Encoding Byte
  68. Set-Content -Path $env:windir\Temp\LogIt\LogIt.psd1 -Value $moduleFile2content -Encoding Byte
  69. If ($d) {Write-Debug "Generated LogIt Module Files"}
  70. import-module $env:windir\Temp\LogIt
  71.  
  72. $dc = "ds4.$env:userdnsdomain"
  73. $computersOU = 'CN=Computers,DC=corp,DC=com'
  74. $computersDefaultOU = 'OU=ComputersDefaultC,DC=corp,DC=com'
  75. $schoolsOU = 'OU=Schools,OU=RootSchools,DC=corp,DC=com'
  76. $schoolsRootOU = 'OU=RootSchools,DC=corp,DC=com'
  77. $employeesOU = 'OU=Employees,OU=RootSchools,DC=corp,DC=com'
  78. $csvPath = 'c:\school\Scripts\schoolsubnets.csv'
  79. $departmentalComputersArray = [System.Collections.ArrayList]@()
  80.  
  81. $schoolSubnetsArray = import-csv -path $csvPath
  82.  
  83. $computersOUArray = Get-ADComputer -filter {(operatingSystem -notlike '*Server*')} -SearchBase $computersDefaultOU -server $DC
  84.  
  85.  
  86. #move from Computers to schools Computers
  87. ForEach ($computer in $computersOUArray)
  88.     {              
  89.         If ([ADSI]::Exists("LDAP://$DC/$computersOU"))
  90.             {
  91.                 If ($d) {Write-Debug "OU path :: LDAP://$DC/$computersDefaultOU :: exists, proceed"}
  92.                 Move-ADObject -Identity $($computer.ObjectGuid) -server $DC -TargetPath $computersDefaultOU -Confirm:$false
  93.             }
  94.     }
  95.  
  96. $computersDefaultOUArray = Get-ADComputer -filter {(operatingSystem -notlike '*Server*')} -SearchBase $computersDefaultOU -server $DC
  97.  
  98.  
  99.  
  100. #Starting main script actions
  101. Write-Output "Starting script actions on $(Get-Date)"
  102. Write-Log -Log $logname -LogLevel "Informational" -LogText "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting script actions on $(Get-Date) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
  103. $i = 0
  104. #Array of computer objects grabbed from AD.
  105. ForEach($computer in $computersDefaultOUArray)
  106.     {#Set the GUID to an easily manipulable\accessible string type
  107.     $i = $i + 1
  108.     $computerHasBeenMoved = $:false
  109.     Write-Output "$($Computer.Name).$env:userdnsdomain"
  110.     $IPTest = Test-Connection -computerName "$($Computer.Name).$env:userdnsdomain" -Count 1 -Quiet -ErrorAction Continue
  111.     If ($IPTest)
  112.         {
  113.             $IPRecord = Test-Connection "$($Computer.Name).$env:userdnsdomain" -Count 1 -ErrorAction Continue
  114.             $iPAddress = $IPRecord.IPV4Address
  115.             Write-Output "$comptuer @ $ipaddress is online"
  116.             Write-Progress -Activity 'Determining whether hosts are online...' -Status "Hosts tested $i" -PercentComplete (($i / $computersDefaultOUArray.Count)*100)
  117.         }
  118.     Else
  119.         {          
  120.             Write-Output 'No such host found'
  121.             Write-Log $logname -LogLevel "Informational" -LogText "$($Computer.Name) is offline"
  122.             Write-Progress -Activity 'Determining whether hosts are online...' -Status "Hosts tested $i" -PercentComplete (($i / $computersDefaultOUArray.Count)*100)
  123.             Continue
  124.         }  
  125.            
  126.     $splitIP = $iPAddress.ToString().Split('.')  
  127.     If ($splitIP[1] -ne '254')#check if the IP is at HQ
  128.         {
  129.             ForEach ($school in $schoolSubnetsArray)#grabbing from a csv file with the headers school,secondoctet,deptnumber and go through all the schools for a match
  130.                 {                
  131.                 [int]$verifyOctet = $splitIP[1]              
  132.                 If ($($school.SecondOctet) -eq $verifyOctet) #if it matches the school's octet, proceed
  133.                     {                                            
  134.                         $TargetOU = Get-ADOrganizationalUnit -LDAPFilter "(Name=$($school.deptNumber)Computers)" -SearchBase $schoolsRootOU -SearchScope Subtree #Get OU at school to put computer in
  135.                         Write-Output $TargetOU
  136.                         Write-Output $TargetOU.DistinguishedName
  137.                         If (!($TargetOU -eq $null))
  138.                             {                                                  
  139.                                 Move-ADObject -Identity $($computer.ObjectGuid) -Server $DC -TargetPath "$($TargetOU.DistinguishedName)" -Confirm:$false -Verbose -whatif #move to school OU                        
  140.                                 Write-Log $logname -LogLevel "Informational" -LogText "$($Computer.Name) @ $iPAddress :: has been moved :: $TargetOUdN"
  141.                                 $computerHasBeenMoved = $:true
  142.                             }
  143.                         Else
  144.                             {
  145.                                 Write-Output "$computer was not moved by subnet, no corresponding department was found for $($school.deptNumber) on subnet 10.$($school.SecondOctet)"
  146.                                 Write-Log $logname -LogLevel "Error" -LogText "$computer was not moved by subnet, no corresponding department was found for $($school.deptNumber) on subnet 10.$($school.SecondOctet)"
  147.                             }
  148.                     }                        
  149.                 }                  
  150.         }
  151.         If (!($computerHasBeenMoved))
  152.                 {
  153.                     $departmentalComputersArray.Add($computer) #add computers here that don't match any octets in list.
  154.                 }
  155.      
  156.     }
  157. Write-Progress -Activity 'Determining whether hosts are online...' -Completed
  158. Write-Output 'Continuing...'
  159. ForEach ($computer in $departmentalComputersArray)
  160.     {
  161.     $DepartmentalOUs = Get-ADOrganizationalUnit -filter * -searchbase $employeesOU -SearchScope OneLevel  
  162.     $computerDeptNum = $computer.Name.SubString(0,4)
  163.        
  164.         ForEach ($DepartmentalOU in $DepartmentalOUs)
  165.             {
  166.                 $DepartmentNumber = $DepartmentalOU.Name.SubString(0,4)
  167.                
  168.                
  169.                 If ($computerDeptNum -eq $DepartmentNumber)
  170.                     {
  171.                        
  172.                         $TargetOU = Get-ADOrganizationalUnit -LDAPFilter "(Name=${computerDeptNumber}Computers)" -SearchBase $employeesOU -SearchScope Subtree #Get OU at school to put computer in
  173.                        
  174.                         If ($TargetOU -ne $Null)
  175.                             {                            
  176.                                 Move-ADObject -Identity $($computer.ObjectGuid) -Server $DC -TargetPath $($TargetOU.DistinguishedName) -Confirm:$false -Verbose -WhatIf #move to school OU
  177.                                 Write-Log $logname -LogLevel "Informational" -LogText "$($Computer.Name) ::has been moved :: $TargetOUdN"
  178.                             }
  179.                         Else
  180.                             {
  181.                                 Write-Output "$($Computer.Name) :: did not move. No OU found for department # $computerDeptNumber"
  182.                                 Write-Log $logname -LogLevel "Error" -LogText "$($Computer.Name) :: did not move. No OU found for department # $computerDeptNumber"
  183.                             }
  184.                        
  185.                     }
  186.             }
  187.     }
  188.  
  189. Write-Output "Finishing script actions on $(Get-Date)"
  190. Write-Log -Log $logname -LogLevel "Informational" -LogText "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finishing script actions on $(Get-Date) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
  191.  
  192. If (Test-Path "$env:windir\Temp\LogIt")
  193.     {
  194.         Write-Output "Deleting LogIt Module folder"
  195.         Get-ChildItem -Path "$env:windir\Temp\LogIt" -recurse | Remove-Item -force -recurse
  196.         Remove-Item "$env:windir\Temp\LogIt"
  197.     }
  198.  
  199. $VerbosePreference = "silentlyContinue"
  200. $DebugPreference = "silentlyContinue"
Advertisement
Add Comment
Please, Sign In to add comment