문제

PowerShell에서 사용하면 응용 프로그램이 파일을 잠그는 지 확인할 수 있습니까?

파일을 사용하는 프로세스/응용 프로그램을 확인하여 파일을 닫을 수 있습니다.

도움이 되었습니까?

해결책

당신은 이것을 할 수 있습니다 sysinternals 도구 핸들 .exe. 다음과 같은 것을 시도하십시오.

PS> $handleOut = handle
PS> foreach ($line in $handleOut) { 
        if ($line -match '\S+\spid:') {
            $exe = $line
        } 
        elseif ($line -match 'C:\\Windows\\Fonts\\segoeui\.ttf')  { 
            "$exe - $line"
        }
     }
MSASCui.exe pid: 5608 ACME\hillr -   568: File  (---)   C:\Windows\Fonts\segoeui.ttf
...

다른 팁

당신은 그것을 사용할 수 있어야합니다 OpenFiles 명령 일반 명령 줄 또는 PowerShell에서.

OpenFiles 내장 도구는 파일 공유 또는 로컬 파일에 사용할 수 있습니다. 로컬 파일의 경우 도구를 켜고 기계를 다시 시작해야합니다 (다시 사용하기 위해). 이 기능을 켜는 명령은 다음과 같습니다.

openfiles /local on

예를 들어 (Windows Vista X64에서 작동) :

openfiles /query | find "chrome.exe"

Chrome과 관련된 파일 핸들을 성공적으로 반환합니다. 파일 이름으로 전달하여 현재 해당 파일에 액세스하는 프로세스를 확인할 수도 있습니다.

이것은 당신에게 도움이 될 수 있습니다 : PowerShell을 사용하여 파일을 잠그는 프로세스를 찾으십시오.. System.diagnostics.processModuleCollection 모듈 각 프로세스의 속성을 구문 분석하고 잠긴 파일의 파일 경로를 찾습니다.

$lockedFile="C:\Windows\System32\wshtcpip.dll"
Get-Process | foreach{$processVar = $_;$_.Modules | foreach{if($_.FileName -eq $lockedFile){$processVar.Name + " PID:" + $processVar.id}}}

사용 솔루션을 찾을 수 있습니다 sysinternal'에스 핸들 공익사업.

PowerShell 2.0과 함께 작업하려면 코드를 수정해야했습니다.

#/* http://jdhitsolutions.com/blog/powershell/3744/friday-fun-find-file-locking-process-with-powershell/ */
Function Get-LockingProcess {

    [cmdletbinding()]
    Param(
        [Parameter(Position=0, Mandatory=$True,
        HelpMessage="What is the path or filename? You can enter a partial name without wildcards")]
        [Alias("name")]
        [ValidateNotNullorEmpty()]
        [string]$Path
    )

    # Define the path to Handle.exe
    # //$Handle = "G:\Sysinternals\handle.exe"
    $Handle = "C:\tmp\handle.exe"

    # //[regex]$matchPattern = "(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\b(\d+)\b)\s+type:\s+(?<Type>\w+)\s+\w+:\s+(?<Path>.*)"
    # //[regex]$matchPattern = "(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\d+)\s+type:\s+(?<Type>\w+)\s+\w+:\s+(?<Path>.*)"
    # (?m) for multiline matching.
    # It must be . (not \.) for user group.
    [regex]$matchPattern = "(?m)^(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\d+)\s+type:\s+(?<Type>\w+)\s+(?<User>.+)\s+\w+:\s+(?<Path>.*)$"

    # skip processing banner
    $data = &$handle -u $path -nobanner
    # join output for multi-line matching
    $data = $data -join "`n"
    $MyMatches = $matchPattern.Matches( $data )

    # //if ($MyMatches.value) {
    if ($MyMatches.count) {

        $MyMatches | foreach {
            [pscustomobject]@{
                FullName = $_.groups["Name"].value
                Name = $_.groups["Name"].value.split(".")[0]
                ID = $_.groups["PID"].value
                Type = $_.groups["Type"].value
                User = $_.groups["User"].value.trim()
                Path = $_.groups["Path"].value
                toString = "pid: $($_.groups["PID"].value), user: $($_.groups["User"].value), image: $($_.groups["Name"].value)"
            } #hashtable
        } #foreach
    } #if data
    else {
        Write-Warning "No matching handles found"
    }
} #end function

예시:

PS C:\tmp> . .\Get-LockingProcess.ps1
PS C:\tmp> Get-LockingProcess C:\tmp\foo.txt

Name                           Value
----                           -----
ID                             2140
FullName                       WINWORD.EXE
toString                       pid: 2140, user: J17\Administrator, image: WINWORD.EXE
Path                           C:\tmp\foo.txt
Type                           File
User                           J17\Administrator
Name                           WINWORD

PS C:\tmp>

나는 좋은 해결책을 보았다 잠긴 파일 감지 PowerShell 및 .NET Framework 클래스 만 사용합니다.

function TestFileLock {
    ## Attempts to open a file and trap the resulting error if the file is already open/locked
    param ([string]$filePath )
    $filelocked = $false
    $fileInfo = New-Object System.IO.FileInfo $filePath
    trap {
        Set-Variable -name filelocked -value $true -scope 1
        continue
    }
    $fileStream = $fileInfo.Open( [System.IO.FileMode]::OpenOrCreate,[System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None )
    if ($fileStream) {
        $fileStream.Close()
    }
    $obj = New-Object Object
    $obj | Add-Member Noteproperty FilePath -value $filePath
    $obj | Add-Member Noteproperty IsLocked -value $filelocked
    $obj
}

나는 명령 프롬프트 (CMD)의 내용이 마음에 들며 PowerShell에서도 사용할 수 있습니다.

tasklist /m <dllName>

DLL 파일의 전체 경로를 입력 할 수는 없습니다. 그 이름 만 충분합니다.

위의 기능을 아래에서 약간 수정하면 아래의 기능을 반환합니다 (완전한 관리자 권한으로 실행해야 함) 예를 들어 :

ps> testfilelock "c : pagefile.sys"

function TestFileLock {
    ## Attempts to open a file and trap the resulting error if the file is already open/locked
    param ([string]$filePath )
    $filelocked = $false
    $fileInfo = New-Object System.IO.FileInfo $filePath
    trap {
        Set-Variable -name Filelocked -value $true -scope 1
        continue
    }
    $fileStream = $fileInfo.Open( [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None )
    if ($fileStream) {
        $fileStream.Close()
    }
    $filelocked
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top