ConeHealth
ConeHealth

Reputation: 1

Deleting files with PowerShell

In the code below I am trying to have files older than 90 days be deleted from a powershell folder. It will delete files older than 90 days, however if I have a subfolder in the powershell folder the files older than 90 days in the subfolder will be deleted as well. Why does this happen with the code below?

Get-ChildItem -Path "C:\powershell" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-90))} | Remove-Item

Upvotes: 0

Views: 73

Answers (1)

Neil
Neil

Reputation: 41

Mathias nailed it first go...

Get-ChildItem -Path "C:\powershell" -File | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-90))} | Remove-Item

-Recurse is only if you need to work through subdirectories below your target, remove that and just use -File and it will only look for files in the target directory. Enjoy!

Upvotes: 2

Related Questions