我在自动化部署时遇到一个问题,停止服务后文件仍然被锁定,导致无法删除。我不想使用等待的方式来解决这个问题,因为这不是一个可靠的方法。是否有一种良好的方式来解决锁定文件的问题,比如某种“等待文件可删除”的方法:
Get-ChildItem:拒绝访问路径“D:\MyDirectory\”。
在这种情况下,“Test-Path”是不够的,因为该文件夹已经存在,而且我也有访问权限。
我在自动化部署时遇到一个问题,停止服务后文件仍然被锁定,导致无法删除。我不想使用等待的方式来解决这个问题,因为这不是一个可靠的方法。是否有一种良好的方式来解决锁定文件的问题,比如某种“等待文件可删除”的方法:
Get-ChildItem:拒绝访问路径“D:\MyDirectory\”。
在这种情况下,“Test-Path”是不够的,因为该文件夹已经存在,而且我也有访问权限。
感谢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}
$file
应为绝对路径,例如:[IO.File]::OpenWrite((Resolve-Path $file).Path).close()
。否则,它将默认为主目录并成为难以调试的逻辑错误。 - mvanle$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
Simplified:
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
}
}