[英]Powershell: Check if a file is locked
我在自动部署时遇到问题,在我停止服务后,文件上仍然存在锁定,我无法删除它。 我真的不想开始用 sleep 来做一些“通常有效”的东西。 有没有一种很好的方法来正确解决锁定文件的问题,也许是某种“等到文件可移动”:
Get-ChildItem:拒绝访问路径“D:\MyDirectory\”。
在这种情况下,“测试路径”是不够的,因为该文件夹都存在并且我可以访问它。
感谢 David Brabant 在最初的问题下发布了指向此解决方案的链接。 看来我可以从以下功能开始:
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
}
}
然后添加一个带有超时的“等待”功能。
谢谢你的帮助!
我用这个:
try { [IO.File]::OpenWrite($file).close();$true }
catch {$false}
$fileName = "C:\000\Doc1.docx"
$file = New-Object -TypeName System.IO.FileInfo -ArgumentList $fileName
$ErrorActionPreference = "SilentlyContinue"
[System.IO.FileStream] $fs = $file.OpenWrite();
if (!$?) {
$msg = "Can't open for write!"
}
else {
$fs.Dispose()
$msg = "Accessible for write!"
}
$msg
简化:
Function Confirm-FileInUse {
Param (
[parameter(Mandatory = $true)]
[string]$filePath
)
try {
$x = [System.IO.File]::Open($filePath, 'Open', 'Read') # Open file
$x.Close() # Opened so now I'm closing
$x.Dispose() # Disposing object
return $false # File not in use
}
catch [System.Management.Automation.MethodException] {
return $true # Sorry, file in use
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.