使用Powershell识别已对DLL进行锁定的进程

时间:2013-10-17 19:58:42

标签: c# powershell dll cmdlets

使用powershell,我想识别放置给定DLL的任何进程锁。

解决。见下文。

2 个答案:

答案 0 :(得分:0)

function IsDLLFree()
{

# The list of DLLs to check for locks by running processes.
$DllsToCheckForLocks = "C:\mydll1.dll","C:\mydll2.dll";

# Assume true, then check all process dependencies
$result = $true;

# Iterate through each process and check module dependencies
foreach ($p in Get-Process) 
{
    # Iterate through each dll used in a given process
    foreach ($m in Get-Process -Name $p.ProcessName -Module -ErrorAction SilentlyContinue)
    {
        # Check if dll dependency matches any DLLs in list
        foreach ($dll in $DllsToCheckForLocks)
        {
            # Compare the fully-qualified file paths, 
            # if there's a match then a lock exists.
            if ( ($m.FileName.CompareTo($dll) -eq 0) )
            {
                $pName = $p.ProcessName.ToString()
                Write-Error "$dll is locked by $pName. Stop this service to release this lock on $m1."
                $result = $false; 
            }
        }
    }
}

return $result;
}

答案 1 :(得分:0)

如果您正在评估当前应用程序域中加载的dll文件,则此方法有效。如果传入dll文件的路径,它将返回是否在当前应用程序域中加载了该程序集。即使您不知道.dll文件(仍然适用于该文件),这一点特别有用,但想知道一般区域是否有带锁的.dll文件。

function Get-IsPathUsed()
{
    param([string]$Path)
    $isUsed = $false

    [System.AppDomain]::CurrentDomain.GetAssemblies() |? {$_.Location -like "*$Path*"} |% {
        $isUsed = $true;
    }

    $isUsed;
}