简体   繁体   中英

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 : 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.

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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