1

Here is a script to remove file/folder older than X days. but then i thought what if any of file or folder is being using by other app. i haven't face such issue yet but i don't think Remove-Item cannot delete file/folder if it's locked/using by other app. is there anyway using powershell we can delete locked file?

Get-ChildItem "folder path" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-1))}| Remove-Item -Recurse -Force -Confirm:$false
Shahpari
  • 115
  • 2
  • 8
  • 1
    Do not do this! The whole point of locking a file is to prevent access outside of the locking application. There are ways to forcibly close file handles, but that will cause issues on the application that holds the file open. – vonPryz Oct 10 '21 at 19:43
  • thank you for the suggestion. but it's okay in my case. – Shahpari Oct 10 '21 at 19:46
  • See [this answer](https://stackoverflow.com/a/958580/45375) for how to find the processes that have a given file locked, but note that that it requires installation of the `handle.exe` SysInternals utility. – mklement0 Oct 10 '21 at 20:33
  • I am pretty sure you are working on an XY problem. A good solution is to notify the lock-holders to close the files. Or terminate the application that holds the lock, if it is stuck. – vonPryz Oct 11 '21 at 07:11
  • what about [this answer](https://stackoverflow.com/a/45714289)? They go through all processes and check if it is locking a file that you are trying to delete and stop the process. No external dependency on windows. – lastlink Jul 06 '22 at 15:05
  • Just to chime in on why this might actually be needed. Autodesk's new ODIS installs. Produces a log file of 100,000 lines for every program installed. Appends so after installing 10+ programs a year for a few years the log file is utterly unusable. Proper solution is delete all those file after successful install. After failed install ZIP them, then delete. BUT, because Windows installers sometimes hold the lock on the log file for as much as 10 minutes after install completes, this is a pain. Would be nice to have a way to force delete when Windows is just being the junk it is. – Gordon Oct 14 '22 at 07:59

1 Answers1

4

On Windows, if the file is locked, you can call the Win32 API MoveFileEx to ask Windows to delete it on the next reboot.

    $Win32 = Add-Type -Passthru -Name Win32 -MemberDefinition '
    [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
    public static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, int dwFlags);'

    $Win32::MoveFileEx($path, [NullString]::Value, 4 <# DelayUntilReboot #> )
Jaykul
  • 15,370
  • 8
  • 61
  • 70