简体   繁体   中英

Delete a locked file using powershell

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

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 #> )
Remove-Item

will delete the locked files as well. Please validate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM