Powershell:检查文件是否被锁定 [英] Powershell: Check if a file is locked
问题描述
我在自动执行部署时遇到问题,在停止服务后,文件上仍然有锁,无法删除它.我真的不想开始沉迷于睡眠以制造通常有用的东西".有没有一种很好的方法来正确解决锁定文件的问题,也许是某种等到文件可移动":
I have a problem with automating a deployment, after I stop the service there is still a lock on the file and I am unable to delete it. I really do not want to start hacking about with sleeps to make something that 'usually works'. Is there a good way to properly resolve the problem of locked files, perhaps some kind of 'wait until file is removable':
Get-ChildItem:拒绝访问路径"D:\ MyDirectory \".
Get-ChildItem : Access to the path 'D:\MyDirectory\' is denied.
在这种情况下,测试路径"还不够,因为该文件夹同时存在并且我可以访问它.
'Test-Path' is not sufficient in this case as the folder both exists and I have access to it.
推荐答案
感谢David Brabant在最初的问题下发布了此解决方案的链接.看来我可以通过以下功能开始做这件事:
With thanks to David Brabant who posted a link to this solution under the initial question. It appears I can do this by starting off with the following function:
function Test-FileLock {
param (
[parameter(Mandatory=$true)][string]$Path
)
$oFile = New-Object System.IO.FileInfo $Path
if ((Test-Path -Path $Path) -eq $false) {
return $false
}
try {
$oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
if ($oStream) {
$oStream.Close()
}
return $false
} catch {
# file is locked by a process.
return $true
}
}
然后添加一个带有超时的等到"功能.
Then add a 'wait until' function with a timeout.
感谢您的帮助!
这篇关于Powershell:检查文件是否被锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!