2

I have nearly 500k of CCTV files in different folder map to X drive and I need to delete all of them with specific timing such as from 12midnight to 6 am only but keeping the remaining regardless of date. how can I do that? I tried using for files but only seems to filter files for the day and timing also incorrect as it basically doesn't show the files within the defined time.

For PowerShell I got this:

Get-ChildItem -Path c:\your\path\here -Recurse |
  Where-Object -FilterScript { $_.LastWriteTime -ge (Get-Date).AddHours(-2) }

but unsure how to modify it to get the list of only 12am to 6am files.

mklement0
  • 382,024
  • 64
  • 607
  • 775
iSpoon
  • 27
  • 6

2 Answers2

2

I think this could be useful. It checks if the LastWriteTime.Hour is greater than 0 (12 am) but less than 6 (6 am):

Get-ChildItem -Path c:\path -Recurse | 
    Where-Object { $_.LastWriteTime.Hour -gt 0 -and $_.LastWriteTime.Hour -lt 6}
I.T Delinquent
  • 2,305
  • 2
  • 16
  • 33
2

Try this. It uses TimeSpans to filter the files between midnight and 6 AM:

$timeAfter  = New-TimeSpan -Hours 0 -Minutes 0 -Seconds 0
$timeBefore = New-TimeSpan -Hours 6 -Minutes 0 -Seconds 0

Get-ChildItem -Path 'X:\TheFolder' -Filter '*.CCTV' -File -Recurse | 
    Where-Object { $_.LastWriteTime.TimeOfDay -gt $timeAfter -and $_.LastWriteTime.TimeOfDay -lt $timeBefore} |
    Remove-Item -WhatIf

Once satisfied with the information shown in the console, remove the -WhatIf switch

Theo
  • 57,719
  • 8
  • 24
  • 41
  • Don't know why it only show a few folder instead of everything – iSpoon Jan 30 '20 at 12:41
  • 2
    @iSpoon Do the files all have the extension `.CCTV` then? Without `-Filter` you are colecting all files, possibly also files you do not want to delete, that's why I put it in. Please let me know what the file extension(s) need to be so I can update the code. (P.S. I added the `-File` switch to make sure you are not getting folder objects) – Theo Jan 30 '20 at 13:29