it-source

파워셸:파일이 잠겨 있는지 확인

criticalcode 2023. 11. 2. 21:50
반응형

파워셸:파일이 잠겨 있는지 확인

배포를 자동화하는 데 문제가 있습니다. 서비스를 중지한 후에도 파일에 잠금이 남아 삭제할 수 없습니다.저는 정말로 '보통 효과가 있는' 무언가를 만들기 위해 잠꼬대를 시작하고 싶지 않습니다.'파일이 제거될 때까지 기다립니다'와 같은 잠금 파일 문제를 적절히 해결할 수 있는 좋은 방법이 있습니까?

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

그런 다음 시간 제한이 있는 'Wait to there' 함수를 추가합니다.

도와주셔서 감사합니다!

나는 이것을(를)

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

언급URL : https://stackoverflow.com/questions/24992681/powershell-check-if-a-file-is-locked

반응형