Yesterday I wrote a PowerShell script that deletes files not accessed for more than 7 days.
Jeff Hicks correctly commented that such a script should be made into a function so that it can be called from the command line with a few parameters.
Basically: “script.ps1 D:\Company\DropBox 7”
First, I started to provide the users a nice little popup where they have to put in the parameters:
function DeleteOldFiles ($TargetPath, $DaysToKeep)
{
foreach ($i in Get-ChildItem $TargetFolder -recurse)
{
if ($i.LastWriteTime -lt ($(Get-Date).AddDays(-$daystokeep)))
{
Remove-Item $File.FullName -force
}}}
Command line: DeleteOldFiles d:\Company\DropBox 7
But… that script deletes all files, not only those with a specific extension. No problem, that is easily put in there:
function DeleteOldFiles ($TargetPath, $DaysToKeep, $Extension)
{
foreach ($i in Get-ChildItem $TargetFolder –recurse –include $Extension)
{
if ($i.LastWriteTime -lt ($(Get-Date).AddDays(-$daystokeep)))
{
Remove-Item $File.FullName -force
}}}
Command line: DeleteOldFiles d:\Company\DropBox 7 .zip
You are on the right path and because this is a great learning exercise I’m going to keep pushing you, if that is ok. First, why not filter the files:
dir -path $targetpath -include $extension -recurse | where {$_.LastWriteTime ….} | remove-item
To me, it looks like you are still thinking in VBScript. Start thinking objects in a pipelined expression. Once you have this down, then start thinking about taking it to the next level with error handling, ie what if I mistype a path? Perhaps adding support for -Whatif? You could add comment based help or parameter validation. The last comment I would make is that when scripting, use standard verbs for your function names. The noun can be flexible. Also keep in mind to use full cmdlet and parameter names, which you seem to be doing. Keep up the good work.