views:

4035

answers:

2

The following script will delete files in a named directory that are older than 14 days and write to a .txt with the path and the files deleted (found this script on another forum..credit to shay):

dir c:\tmp -recurse | where {!$.PsIsContainer -AND $.lastWriteTime -lt (Get-Date).AddDays(-14) } | select LastWriteTime,@{n="Path";e={convert-path $_.PSPath}} | tee c:\oldFiles.txt | Remove-Item -force -whatif

I have 3 questions:

  1. What is -lt and what is -le and what is -gt? When would I use each one
  2. The script above only deletes file...how can I delete folders as well?
  3. The script above is based off of LastWriteTime .. what about CreatedDate or LastAccessed time?
+2  A: 

The -lt -le and -gt are comparison operators instead of <, <=, >. Type "help about_Comparison_Operators" at the powershell command prompt for the details on each type and the reason for using these instead of the ones you are familiar with from other languages.

To delete folders as well you need to remove the !$.PsIsContainer AND part of the where filter. This is removing all items from the lists that are directories.

I'm not sure what you are after with the question "what about CreatedDate or LastAccessed time" but you can simply use these properties in a similar way as LastWriteTime but you need to decide on the logic you are trying to achieve.

Martin Hollingsworth
+5  A: 

Ok, here we go:

  1. -lt, -le and -gt are comparison operators. lt means less than, le means less or equal than, and gt means greater than.

  2. Removing folders can get dangerous if you do not have control over what gets inside it. You might have problems and please be aware of data loss. You can delete folders by using the same Remove-Item cmdlet, just by playing with its options. Check this article, it has great instructions on how to achieve it: http://searchwindowsserver.techtarget.com/generic/0,295582,sid68_gci1275887,00.html

  3. Usually, for files that have been sitting there for a while, LastWriteTime and CreatedDate and LastAccessTime will be the same. In a read-only file, like a DLL, LastAccessTime might be newer than the other two. In a read/write file (like outlook's pst file) WriteTime and AccessTime might be the same. Basically, that's totally up to you. They work as the same way as LastWriteTime does. Consider the nature of the files you want to delete, and go ahead!

Macalendas
To be more specific, the condition removing folders from the list is this: !$.PsIsContainer
JasonMArcher