반응형
파워셸:파일이 잠겨 있는지 확인
배포를 자동화하는 데 문제가 있습니다. 서비스를 중지한 후에도 파일에 잠금이 남아 삭제할 수 없습니다.저는 정말로 '보통 효과가 있는' 무언가를 만들기 위해 잠꼬대를 시작하고 싶지 않습니다.'파일이 제거될 때까지 기다립니다'와 같은 잠금 파일 문제를 적절히 해결할 수 있는 좋은 방법이 있습니까?
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
반응형
'it-source' 카테고리의 다른 글
MS Word 문서에서 구문 강조 표시 (0) | 2023.11.02 |
---|---|
포스트렌더 "플리커"를 제거하는 방법은? (0) | 2023.11.02 |
워드프레스 웹사이트에서 json 응답을 얻는 방법 (0) | 2023.11.02 |
스프링 프로토타입 범위 - 사용 사례? (0) | 2023.11.02 |
유연한 어레이 멤버로 인해 정의되지 않은 동작이 발생할 수 있습니까? (0) | 2023.11.02 |