Quantcast
Channel: Windows PowerShell Forum
Viewing all articles
Browse latest Browse all 2314

Script zum Leeren von Temp Ordnern

$
0
0

Hallo allerseits!

Ich hab mir hier ein Script zusammengebaut, welches aus den Temp Ordnern aller lokalen Profile sowie des Systems alle Inhalte löschen soll, die älter als 30 Tage sind. Das Script wird beim Systemstart eines Clients automatisch ausgeführt. Allerdings werden irgendwie nicht alle Elemente gelöscht und vor allem sieht das für mich alles so aus, als würde ich das viel zu umständlich angehen. ;-)

Hat jemand eine Idee, wie sich das Script optimieren ließe?

Write-Host "* Cleanup TEMP Folder Script" -foregroundcolor Cyan

Function DeleteOldFiles([string]$directory)
{
  Get-ChildItem $directory -recurse -force -ErrorAction SilentlyContinue | Where {$_.LastWriteTime -lt (Get-Date).adddays(-30) -and -not $_.psiscontainer} |% {
    If (Remove-Item $_.fullname -force -ErrorAction SilentlyContinue) {
	  $LogMessage = "Removing "+$_.fullname
      Write-Host $LogMessage
      Write-Eventlog -Logname Application -Source DelTemp -EventID 2005 -EntryType Information -Message $LogMessage
	}
  }  
  Get-ChildItem -Path $directory -ErrorAction SilentlyContinue | ForEach-Object {
    If ($_.PSIsContainer -eq $true) {
      If ((Get-ChildItem -Path $_.FullName -ErrorAction SilentlyContinue) -eq $null) {
		If (Remove-Item $($_.FullName) -force -ErrorAction SilentlyContinue) {
		  $LogMessage = "Removing "+$($_.FullName)
		  Write-Host $LogMessage
          Write-Eventlog -Logname Application -Source DelTemp -EventID 2005 -EntryType Information -Message $LogMessage
		}
      }
    }
  }   
}

Function DeleteProfileDir([string]$directory)
{
  Write-Host "Checking profile path" $directory
  $tempdir=$directory+"\AppData\Local\Temp"
  If (Test-Path $tempdir -ErrorAction SilentlyContinue)
  {
    Write-Host "Cleaning" $tempdir
    DeleteOldFiles($tempdir)
  }
}

New-Eventlog -Logname Application -Source DelTemp -ErrorAction SilentlyContinue
Write-Eventlog -Logname Application -Source DelTemp -EventID 2001 -EntryType Information -Message "DelTemp Script started."
$profiledirs=Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList' | % {Get-ItemProperty $_.pspath } | Select profileImagePath | ForEach-Object -process {DeleteProfileDir $_.ProfileImagePath}
$wintemp=$env:Windir+"\TEMP"
Write-Host "Cleaning" $wintemp
DeleteOldFiles($wintemp)
Write-Eventlog -Logname Application -Source DelTemp -EventID 2002 -EntryType Information -Message "DelTemp Script finished."


Viewing all articles
Browse latest Browse all 2314


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>