cosine83

Delete temp files

Mar 2nd, 2014
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #PowerShell script to clean out temporary folders
  2.  
  3. #Load Active Directory PowerShell Module
  4. Import-Module activedirectory
  5.  
  6. #Variable array for folders to clean, others can be added as needed
  7. $tempRM = @("C:\Windows\Temp\*", "C:\Windows\Prefetch\*", "C:\Documents and Settings\*\Local Settings\temp\*", "C:\Users\*\Appdata\Local\Temp\*")
  8. $tempUNC = @("\\$computer\c$\Windows\Temp\*", "\\$computer\c$\Windows\Prefetch\*", "\\$computer\c$\Documents and Settings\*\Local Settings\temp\*", "\\$computer\c$\Users\*\Appdata\Local\Temp\*")
  9.  
  10. #AD Path to search for computers to clean
  11. $searchbase = "OU=derp,OU=Computers,OU=derp,DC=domain,DC=com"
  12.  
  13. #Get the list of computers to clean
  14. $query = Get-ADComputer -Filter * -SearchBase $searchbase | Select DNSHostName | Sort DNSHostName
  15. $computers = $query.DNSHostName
  16.  
  17. #Operation to clear out temp files in specified folders
  18. #WinRM method requires winrm quickconfig -q to be run on host machines first, psexec command above should take care of that
  19. #UNC method requires the credentials provided above to have access to admin shares
  20.  
  21. Try {
  22. foreach ($computer in $computers)
  23.     {
  24.         Write-Host "$computer - Connecting..."
  25.         if(Test-Connection $computer -Count 1 -Quiet)
  26.         {
  27.                 Write-Host -ForegroundColor Green "$computer - Deleting files!"
  28.                 Invoke-Command -ComputerName $computer -ScriptBlock { foreach ($folder in $using:tempRM) {Remove-Item -Path $folder -Recurse -Force -ErrorAction SilentlyContinue} }
  29.                 Write-Host -ForegroundColor Green "$computer - Done!"
  30.         }
  31.             else
  32.             {
  33.                 Write-Host -ForegroundColor Red "$computer - Offline!"
  34.             }
  35.     }
  36. }  
  37. Catch {
  38. foreach ($computer in $computers) {
  39.     Write-Host -ForegroundColor Green "$computer - Deleting files!"
  40.     Remove-Item -path $tempUNC -force -recurse
  41.     Write-Host -ForegroundColor Green "$computer - Done!"
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment