简体   繁体   中英

Windows PowerShell - Delete Files Older than X Days

I am currently new at PowerShell and I have created a script based on gathered information on the net that will perform a Delete Operation for found files within a folder that have their LastWriteTime less than 1 day.

Currently the script is as follows:

$timeLimit = (Get-Date).AddDays(-1) 
$oldBackups = Get-ChildItem -Path $dest -Recurse -Force -Filter "backup_cap_*" |
                Where-Object {$_.PSIsContainer -and $_.LastWriteTime -lt $timeLimit}

foreach($backup in $oldBackups)
{
    Remove-Item $dest\$backup -Recurse -Force -WhatIf
}

As far as I know the -WhatIf command will output to the console what the command "should" do in real-life scenarios. The problem is that -WhatIf does not output anything and even if I remove it the files are not getting deleted as expected.

The server is Windows 2012 R2 and the command is being runned within PowerShell ISE V3.

When the command will work it will be "translated" into a task that will run each night after another task has finished backing up some stuff.

I did it in the pipe

Get-ChildItem C:\temp | ? { $_.PSIsContainer -and $_.LastWriteTime -lt $timeLimit } | Remove-Item -WhatIf

This worked for me. So you don't have to ttake care of the right path to the file.

other solution

$timeLimit = (Get-Date).AddDays(-1) 
Get-ChildItem C:\temp2 -Directory | where LastWriteTime -lt $timeLimit  | Remove-Item -Force -Recurse

The original issue was $dest\\$backup would assume that each file was in the root folder. But by using the fullname property on $backup , you don't need to statically define the directory.

One other note is that Remove-Item takes arrays of strings, so you also could get rid of the foreach

Here's the fix to your script, without using the pipeline. Note that since I used the where method this requires at least version 4

$timeLimit = (Get-Date).AddDays(-1) 
$Backups = Get-ChildItem -Path $dest -Directory -Recurse -Force -Filter "backup_cap_*"
$oldBackups = $backups.where{$_.LastWriteTime -lt $timeLimit}
Remove-Item $oldBackups.fullname -Recurse -Force -WhatIf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM