Josh Weatherly
Josh Weatherly

Reputation: 1730

Powershell deleting more files than it should, bug?

I'm using the following snippet of code in a powershell script to clean up files that we no longer need, however this appears to delete everything (thank God for backups...) and not just those modified older than $limit, can anyone explain this behavior?

param (
    [int]$daystokeep = 548 # default to 18 months 
)

$limit = (Get-Date).AddDays(-1 * $daystokeep) # 18 months

Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.ModifyTime -lt $limit } | Remove-Item -Force

Upvotes: 0

Views: 52

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

FileInfo objects have no ModifyTime property, so your comparison basically evaluates to:

$null -lt $limit

which is always $true.

Change the property name to LastWriteTime:

$_.LastWriteTime -lt $limit

Upvotes: 4

Related Questions