Removing files by time period

1

I have a script to remove a file leaving only the last defined ones in the day

Script:

$Now = Get-Date
$Days = 30
$TargetFolder = "C:\LOG"
$Extension = "*.*"
$LastWrite = $Now.AddDays(-$Days)
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where {$_.LastWriteTime -le "$LastWrite"}

foreach ($File in $Files)
        {
            if ($File -ne $NULL)
                {
                    write-host "Deletando arquivo $File" -ForegroundColor "DarkRed"
                    Remove-Item $File.FullName | out-null
                }
            else
                {
                    Write-Host "Nao ha arquivos a serem excluidos!" -foregroundcolor "Green"
                }
        }

It turns out that on my computer (Windows 7 64bits) works perfectly already on the server (Win2008 R2 64bit) it presents the following error:

  

Confirm The item at   Microsoft.PowerShell.Core \ FileSystem :: E: \ LOG \ Maplink.Service.Monitor.HourlyTasks   has children and the Recurse parameter was not specified. If you   continue, all children will be removed with the item. Are you sure you?   wan to continue? [Y] Yes [A] Yes to All [N] No [L] No to All [S]   Suspend [?] Help (default is "Y"):

    
asked by anonymous 11.11.2014 / 14:50

1 answer

1

I was able to solve, I was missing a parameter: Solution replacing Where with the script below:

Where-Object {!$_.PSIsContainer -and $_.LastWriteTime -le $Date}
    
06.01.2015 / 12:24