locked
Disk space cleanup on base of age RRS feed

  • Question

  • I want to create powershell script to have Disk space cleanup on base of file modified date or day

    it fails to run the script. a help is appreciated

    Get-ChildItem "%Windows%\Temp\apt*%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-1))}| Remove-Item"
    Get-ChildItem "%Windows%\$NTServicePackUninstall$%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-60))}| Remove-Item"
    Get-ChildItem "%Windows%\memory.dmp%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-60))}| Remove-Item"
    Get-ChildItem "%Windows%\SoftwareDistribution\Download\"%file and folders%%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-60))}| Remove-Item"
    Get-ChildItem "%Windows%\$NtUninstallKB*$%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-90))}| Remove-Item"
    Get-ChildItem "%Windows\$Recycle.Bin%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-00))}| Remove-Item"
    Get-ChildItem "%Windows\Temp\temp files*%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-60))}| Remove-Item"
    Get-ChildItem "%Windows%\system32\LogFiles\w3svc1\ex*.log%" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-45))}| Remove-Item"

    Monday, October 22, 2018 5:58 PM

All replies

  • the main issue with your code - it tries to delete subfolders with content without "-Recurse" parameter.

    Also make sure you run the script as Administrator or SYSTEM.

    Correct code:

    Get-ChildItem 'C:\path\to\folder' | where { $_.LastWriteTime -le (get-date).AddDays(-1)} | foreach { Remove-Item $_.FullName -Recurse -Force }


    Monday, October 29, 2018 10:05 PM
  • What's the error message?  %windir% in powershell is done like this:  $env:windir.  If you only want to delete files:

    Get-ChildItem $env:Windir\Temp\apt* -File -Recurse |
    Where-Object LastWriteTime -lt (Get-Date).AddDays(-1) | 
    Remove-Item

    • Edited by JS2010 Tuesday, October 30, 2018 8:48 PM
    Tuesday, October 30, 2018 9:39 AM