PowerShell – Delete files based on “LastAccessTime”

powershell

I'm trying to run a command that is supposed to delete anything with the "LastAccessTime" older than 30 days. However, when I run it, it just modifies the LastAccessTime and doesn't delete. Command is below.

Get-ChildItem '\servername\share\folder in the share' | ?{$.LastAccessTime -lt (Get-Date).AddDays(-30)} | ?{!$.psiscontainer} | Remove-Item

The account I'm running this as has access to the share, including delete access (tested this manually). If I take out | Remove-Item and change the days to be older than 1 day, it returns the files. Should I use something other than Remove-Item?

Best Answer

Please avoid using aliases in your script here on serverfault, as they decrease the readability of scripts.

Apart from that, your missing some underscores, I'm guessing your script should read:

Get-ChildItem '\servername\share\folder in the share' | where {$_.LastAccessTime -lt (Get-Date).AddDays(-30)} | where {!$_.psiscontainer} | Remove-Item