0

I have the following code

$top = Get-ChildItem -File C:\SomeFolder\1\ -Recurse -filter *.evtx
foreach ($file in $top) {
    $get = (Get-WinEvent -Path C:\SomeFolder\1\$file  -erroraction 'silentlycontinue').count
    if ($get -eq '0') {
        Remove-Item -Path  C:\SomeFolder\1\$file -Recurse -Force
    }
}

The problem is that the files that I'm trying to delete are in use by the loop.
The following error appears - "Remove-Item : Cannot remove item The process cannot access the file because it is being used by another process."
I even tried exiting with break but it didn't help. Any suggestions?

Thanks!

Sage Pourpre
  • 9,932
  • 3
  • 27
  • 39
Rusty cole
  • 90
  • 9
  • you may be able to gather those files into another $Var and - after the 1st loop finishes - delete them then. – Lee_Dailey Jan 30 '22 at 11:07
  • 2
    Try as @Lee_Dailey suggested, but insert a `[System.GC]::Collect()` call before the delete loop, to make sure any reference(s) to the files be closed. – zett42 Jan 30 '22 at 11:52
  • Could be you need to stop the Windows Eventlog Service (EventLog) first, run the code and start it again. – Theo Jan 30 '22 at 11:59
  • Thanks for the replays. I tried zett42 suggestion, it worked partially. some of the files have been deleted, a few others are still returning " being used by another process". this behavior is very strange. – Rusty cole Jan 30 '22 at 12:17
  • What would happen if you create an array of paths of the logs you need to delete and attempt to delete them (_after ending the loop_)? – Santiago Squarzon Jan 30 '22 at 15:02
  • Try to call the GC twice, as shown here: https://stackoverflow.com/a/8837636/7571258 . You may also add a retry-loop for `Remove-Item`. E. g. if it fails the first time, wait a few seconds, rinse and repeat. – zett42 Jan 30 '22 at 17:54

0 Answers0