簡體   English   中英

Powershell:檢查文件是否被鎖定

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM