script de PowerShell para comprobar una aplicación que está el bloqueo de un archivo?

StackOverflow https://stackoverflow.com/questions/958123

  •  12-09-2019
  •  | 
  •  

Pregunta

El uso de PowerShell, ¿cómo puedo comprobar si una aplicación está bloqueando un archivo?

Me gusta comprobar qué proceso / aplicación está utilizando el archivo, de modo que pueda cerrarla.

¿Fue útil?

Solución

Puede hacer esto con la SysInternals herramienta Handle.exe . Intentar algo como esto:

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

Otros consejos

Usted debe ser capaz de utilizar el openfiles comando desde la línea de comandos regular o de PowerShell.

Los openfiles herramienta integrada se pueden utilizar recursos compartidos de archivos o archivos locales. Para los archivos locales, debe activar la herramienta y reiniciar la máquina (de nuevo, sólo para el primer uso). Creo que el comando para activar esta función es la siguiente:

openfiles /local on

Por ejemplo (funciona en Windows Vista x64):

openfiles /query | find "chrome.exe"

Ese archivo se devuelve correctamente maneja asocia con Chrome. También se puede pasar un nombre de archivo para ver el proceso de acceso a ese archivo actualmente.

Esto podría ayudarle a: uso PowerShell para averiguar qué proceso bloquea un archivo . Se analiza la propiedad System.Diagnostics.ProcessModuleCollection Módulos de cada proceso y busca la ruta de archivo del archivo bloqueado:

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

Puede encontrar una solución utilizando Sysinternal 's Handle utilidad.

I tuvo que modificar el código (ligeramente) para trabajar con 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

Ejemplo:

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>

He visto una buena solución a Locked detección de archivos que utiliza sólo PowerShell y .NET clases del 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
}

Me gustaría que la línea de comandos (CMD) tiene, y puede ser utilizado en PowerShell, así:

tasklist /m <dllName>

Ten en cuenta que no se puede introducir la ruta completa del archivo DLL. Sólo el nombre es lo suficientemente bueno.

Si modifica la función de arriba ligeramente, como a continuación se volverá Verdadero o Falso (Necesitará para ejecutar con derechos de administrador completos) p.ej. Uso:

  

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top