简体   繁体   English

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'.我真的不想开始用 sleep 来做一些“通常有效”的东西。 Is there a good way to properly resolve the problem of locked files, perhaps some kind of 'wait until file is removable':有没有一种很好的方法来正确解决锁定文件的问题,也许是某种“等到文件可移动”:

Get-ChildItem : Access to the path 'D:\MyDirectory\' is denied. Get-ChildItem:拒绝访问路径“D:\MyDirectory\”。

'Test-Path' is not sufficient in this case as the folder both exists and I have access to it.在这种情况下,“测试路径”是不够的,因为该文件夹都存在并且我可以访问它。

With thanks to David Brabant who posted a link to this solution under the initial question.感谢 David Brabant 在最初的问题下发布了指向此解决方案的链接。 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.然后添加一个带有超时的“等待”功能。

Thanks for your help!谢谢你的帮助!

I use this:我用这个:

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

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
    }
}

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

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