Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <#
- .SYNOPSIS
- Powershell script to move computers into designated Schools\Employees Sub-OUs
- .DESCRIPTION
- Queries the default container, pings host, if online, moves based on IP, if 10.254, goes by dept number.
- .PARAMATER
- -debug "turns on visible debugging, warning all ye who enter here, your eyes shall bleed"
- .EXAMPLE
- .\computersOUCleanUp.ps1
- .OUTPUTS
- log file, C:\Windows\Temp\Logs\computersOUCleanUp$date.log
- .NOTES
- Name: computersOUCleanUp.ps1
- Author: \u\Smartguy5000
- Last Modified: 05/11/2016 10:20
- .CHANGELOG
- v1.0 Intitial write
- v1.1 Improved syntax of some variables. Removed unnecessary functions
- v1.2 fixed departmental computers section
- .VERSION
- 1.2
- .LINK
- #>
- [CmdletBinding()]
- Param(
- )
- If ($PSCmdlet.MyInvocation.BoundParameters["Debug"].IsPresent)
- {
- $DebugPreference="Continue"
- $d = $:true
- If ($d) {Write-Debug "Debug Output activated"}
- }
- Else
- {
- $d = $:false
- $DebugPreference="SilentlyContinue"
- }
- #logging module files have not been sanitized
- $moduleFile1 = ""
- $moduleFile2 = ""
- $moduleFile1content = [System.Convert]::FromBase64String($moduleFile1)
- $moduleFile2content = [System.Convert]::FromBase64String($moduleFile2)
- $VerbosePreference = "continue"
- $tempDate = get-date -Uformat %D
- $currentDate = $tempDate -replace "/", "-"
- $logname = "$env:windir\Temp\logs\" + "computersOUCleanUp" + $currentDate + ".log"
- $ErrorActionPreference = "Stop"
- Write-Verbose "Variables have been declared"
- Write-Verbose "## ----------------------------------------------------------------"
- ##----------------------------------------------------------------
- ## environment setup
- Write-Verbose "Setting up environment"
- If (!(Test-Path $env:windir\Temp\LogIt))
- {
- If ($d) {Write-Debug "Creating Logging Module folder"}
- New-Item -ItemType Directory -Path $env:windir\Temp\LogIt | Out-Null
- }
- If(!(Test-Path $env:windir\Temp\Logs))
- {
- If ($d) {Write-Debug "Creating logs directory"}
- New-Item -ItemType Directory -Path $env:windir\Temp\Logs | Out-Null
- }
- Set-Content -Path $env:windir\Temp\LogIt\LogIt.psm1 -Value $moduleFile1content -Encoding Byte
- Set-Content -Path $env:windir\Temp\LogIt\LogIt.psd1 -Value $moduleFile2content -Encoding Byte
- If ($d) {Write-Debug "Generated LogIt Module Files"}
- import-module $env:windir\Temp\LogIt
- $dc = "ds4.$env:userdnsdomain"
- $computersOU = 'CN=Computers,DC=corp,DC=com'
- $computersDefaultOU = 'OU=ComputersDefaultC,DC=corp,DC=com'
- $schoolsOU = 'OU=Schools,OU=RootSchools,DC=corp,DC=com'
- $schoolsRootOU = 'OU=RootSchools,DC=corp,DC=com'
- $employeesOU = 'OU=Employees,OU=RootSchools,DC=corp,DC=com'
- $csvPath = 'c:\school\Scripts\schoolsubnets.csv'
- $departmentalComputersArray = [System.Collections.ArrayList]@()
- $schoolSubnetsArray = import-csv -path $csvPath
- $computersOUArray = Get-ADComputer -filter {(operatingSystem -notlike '*Server*')} -SearchBase $computersDefaultOU -server $DC
- #move from Computers to schools Computers
- ForEach ($computer in $computersOUArray)
- {
- If ([ADSI]::Exists("LDAP://$DC/$computersOU"))
- {
- If ($d) {Write-Debug "OU path :: LDAP://$DC/$computersDefaultOU :: exists, proceed"}
- Move-ADObject -Identity $($computer.ObjectGuid) -server $DC -TargetPath $computersDefaultOU -Confirm:$false
- }
- }
- $computersDefaultOUArray = Get-ADComputer -filter {(operatingSystem -notlike '*Server*')} -SearchBase $computersDefaultOU -server $DC
- #Starting main script actions
- Write-Output "Starting script actions on $(Get-Date)"
- Write-Log -Log $logname -LogLevel "Informational" -LogText "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Starting script actions on $(Get-Date) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
- $i = 0
- #Array of computer objects grabbed from AD.
- ForEach($computer in $computersDefaultOUArray)
- {#Set the GUID to an easily manipulable\accessible string type
- $i = $i + 1
- $computerHasBeenMoved = $:false
- Write-Output "$($Computer.Name).$env:userdnsdomain"
- $IPTest = Test-Connection -computerName "$($Computer.Name).$env:userdnsdomain" -Count 1 -Quiet -ErrorAction Continue
- If ($IPTest)
- {
- $IPRecord = Test-Connection "$($Computer.Name).$env:userdnsdomain" -Count 1 -ErrorAction Continue
- $iPAddress = $IPRecord.IPV4Address
- Write-Output "$comptuer @ $ipaddress is online"
- Write-Progress -Activity 'Determining whether hosts are online...' -Status "Hosts tested $i" -PercentComplete (($i / $computersDefaultOUArray.Count)*100)
- }
- Else
- {
- Write-Output 'No such host found'
- Write-Log $logname -LogLevel "Informational" -LogText "$($Computer.Name) is offline"
- Write-Progress -Activity 'Determining whether hosts are online...' -Status "Hosts tested $i" -PercentComplete (($i / $computersDefaultOUArray.Count)*100)
- Continue
- }
- $splitIP = $iPAddress.ToString().Split('.')
- If ($splitIP[1] -ne '254')#check if the IP is at HQ
- {
- ForEach ($school in $schoolSubnetsArray)#grabbing from a csv file with the headers school,secondoctet,deptnumber and go through all the schools for a match
- {
- [int]$verifyOctet = $splitIP[1]
- If ($($school.SecondOctet) -eq $verifyOctet) #if it matches the school's octet, proceed
- {
- $TargetOU = Get-ADOrganizationalUnit -LDAPFilter "(Name=$($school.deptNumber)Computers)" -SearchBase $schoolsRootOU -SearchScope Subtree #Get OU at school to put computer in
- Write-Output $TargetOU
- Write-Output $TargetOU.DistinguishedName
- If (!($TargetOU -eq $null))
- {
- Move-ADObject -Identity $($computer.ObjectGuid) -Server $DC -TargetPath "$($TargetOU.DistinguishedName)" -Confirm:$false -Verbose -whatif #move to school OU
- Write-Log $logname -LogLevel "Informational" -LogText "$($Computer.Name) @ $iPAddress :: has been moved :: $TargetOUdN"
- $computerHasBeenMoved = $:true
- }
- Else
- {
- Write-Output "$computer was not moved by subnet, no corresponding department was found for $($school.deptNumber) on subnet 10.$($school.SecondOctet)"
- 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)"
- }
- }
- }
- }
- If (!($computerHasBeenMoved))
- {
- $departmentalComputersArray.Add($computer) #add computers here that don't match any octets in list.
- }
- }
- Write-Progress -Activity 'Determining whether hosts are online...' -Completed
- Write-Output 'Continuing...'
- ForEach ($computer in $departmentalComputersArray)
- {
- $DepartmentalOUs = Get-ADOrganizationalUnit -filter * -searchbase $employeesOU -SearchScope OneLevel
- $computerDeptNum = $computer.Name.SubString(0,4)
- ForEach ($DepartmentalOU in $DepartmentalOUs)
- {
- $DepartmentNumber = $DepartmentalOU.Name.SubString(0,4)
- If ($computerDeptNum -eq $DepartmentNumber)
- {
- $TargetOU = Get-ADOrganizationalUnit -LDAPFilter "(Name=${computerDeptNumber}Computers)" -SearchBase $employeesOU -SearchScope Subtree #Get OU at school to put computer in
- If ($TargetOU -ne $Null)
- {
- Move-ADObject -Identity $($computer.ObjectGuid) -Server $DC -TargetPath $($TargetOU.DistinguishedName) -Confirm:$false -Verbose -WhatIf #move to school OU
- Write-Log $logname -LogLevel "Informational" -LogText "$($Computer.Name) ::has been moved :: $TargetOUdN"
- }
- Else
- {
- Write-Output "$($Computer.Name) :: did not move. No OU found for department # $computerDeptNumber"
- Write-Log $logname -LogLevel "Error" -LogText "$($Computer.Name) :: did not move. No OU found for department # $computerDeptNumber"
- }
- }
- }
- }
- Write-Output "Finishing script actions on $(Get-Date)"
- Write-Log -Log $logname -LogLevel "Informational" -LogText "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finishing script actions on $(Get-Date) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
- If (Test-Path "$env:windir\Temp\LogIt")
- {
- Write-Output "Deleting LogIt Module folder"
- Get-ChildItem -Path "$env:windir\Temp\LogIt" -recurse | Remove-Item -force -recurse
- Remove-Item "$env:windir\Temp\LogIt"
- }
- $VerbosePreference = "silentlyContinue"
- $DebugPreference = "silentlyContinue"
Advertisement
Add Comment
Please, Sign In to add comment