Powershell_Toddler
Powershell_Toddler

Reputation: 3

Powershell script to delete files older than x days, but not folders

I have a script that I thought was working, but I'm getting reports that its deleting folders instead of just files. Can someone help me adjust my script to account for this? Do I need to add a -file filter?

$Path = "D:\AppData\Downloads"

$Limit = (Get-Date).AddDays(-6)

Get-ChildItem -path $Path -Recurse -force | Where-Object {!$_.PSIsContainer -and $_.CreationTime -lt $Limit } | Remove-Item -recurse -Force

Upvotes: 0

Views: 5126

Answers (1)

Matt
Matt

Reputation: 46710

You Where-Object clause is most likely not working like you expect it to.

{!$_.PSIsContainer -and $_.CreationTime -lt $Limit } 

Should be

{!$_.PSIsContainer -and ($_.CreationTime -lt $Limit)} 

The brackets ensure the second logical comparison is evaluated independantly. See about_logical_operators for more information

The Windows PowerShell logical operators evaluate only the statements required to determine the truth value of the statement. If the left operand in a statement that contains the and operator is FALSE, the right operand is not evaluated. If the left operand in a statement that contains the or statement is TRUE, the right operand is not evaluated. As a result, you can use these statements in the same way that you would use the If statement.

Also since it is removing files and not folders the -Recurse for Remove-Item seems unnecessary. From the comment by Alroc: Assuming you have version 3 or above of PowerShell you can simplify this by using the -File parameter of Get-ChildItem in place of the !$_.PSIsContainer clause of your Where-Object (which is what was commonly done in Version 2.) Just like you have in your comment:

Get-ChildItem -path $Path -file -Recurse -force | Where-Object {$_.CreationTime -lt $Limit }

Upvotes: 2

Related Questions