I have the following script, that works fine, listing the candidate files to be remove. But I cannot figure it out where or how to add the Remove-Item
instruction to actually delete the files, without losing the export file.
By the way, a Write-Host log wouldn't satisfy as I need to record size of files, last write time, etc. It must be a CSV export (as the one I have with this script).
Of course I can re-run the Get-ChildItem
and instead to pipe out to Select-Object
, pipe out to Remove-Item
, but it would imply a great loss of time.
My script:
$EXTERNALFILE = "C:\DataCleaning\Scripts\FilesToRemove.txt"
$DESTINATION_DIR = "C:\DataCleaning\Logs\"
$LOGFILECSV = "${DESTINATION_DIR}\Removed_$(Get-Date -f yyyy-MM-dd_hh-mm-ss).csv"
$List = Get-Content $EXTERNALFILE
$REPORT = foreach ($Data in $List) {
$Data = $Data -split(';')
$SOURCEDIR = $Data[0]
$FILTERMASK = $Data[1]
$RETENTION = (Get-Date).AddMonths(-$Data[2])
Get-ChildItem -LiteralPath $SOURCEDIR -File -Recurse |
Where-Object {($_.LastWriteTime –lt $RETENTION) -and ($_.Extension -notmatch $FILTERMASK)} |
Select-Object FullName, LastWriteTime, CreationTime,
@{Name="Size (MB)";Expression={[Math]::Round($_.Length /1MB, 2)}},
@{Name="Age (Days)";Expression={(((Get-Date) - $_.LastWriteTime).Days)}}
}
$REPORT | Export-Csv -Delimiter "|" -NoTypeInformation -Encoding UTF8 -Path $LOGFILECSV