简体   繁体   English

使用 powershell 删除锁定的文件

[英]Delete a locked file using powershell

Here is a script to remove file/folder older than X days.这是一个删除超过 X 天的文件/文件夹的脚本。 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.我还没有遇到这样的问题,但我不认为Remove-Item不能删除文件/文件夹,如果它被其他应用程序锁定/使用。 is there anyway using powershell we can delete locked file?无论如何使用 powershell 我们可以删除锁定的文件吗?

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.在 Windows 上,如果文件被锁定,您可以调用 Win32 API MoveFileEx要求 Windows 在下次重新启动时将其删除。

    $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请验证

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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