Powershell: Check if a file is locked

前端 未结 3 481
小鲜肉
小鲜肉 2020-11-28 09:08

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

相关标签:
3条回答
  • 2020-11-28 09:19
    $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
    
    0 讨论(0)
  • 2020-11-28 09:20

    I use this:

    try { [IO.File]::OpenWrite($file).close();$true }
    catch {$false}
    
    0 讨论(0)
  • 2020-11-28 09:31

    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.

    Thanks for your help!

    0 讨论(0)
提交回复
热议问题