7

Remove-Item command does not delete files which are in use. Is there any way where we can delete all the files irrespective of their state?

abhinay kumar
  • 81
  • 1
  • 1
  • 4

1 Answers1

2

You can do this is by finding the processes that are using the file then stop the processess.You can then delete the file after.

$allProcesses = Get-Process
#$lockedFile is the file path
foreach ($process in $allProcesses) { 
$process.Modules | where {$_.FileName -eq $lockedFile} | Stop-Process
-Force -ErrorAction SilentlyContinue
    }
Remove-Item $lockedFile
Code Demon
  • 1,256
  • 1
  • 9
  • 15
  • 3
    And what if the file is in a network drive, in use by other users in other machines? Is there a way to delete the file without stopping processes? – sɐunıɔןɐqɐp Feb 13 '20 at 14:06