Question

Using powershell, I want to identify any process locks placed a given DLL.

Solved. See below.

Was it helpful?

Solution

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

OTHER TIPS

This works if you're assessing dll files loaded in the current application domain. If you pass in the path to the dll file it will return whether or not that assemblies is loaded in the current application domain. This is particularly useful even if you don't know the .dll file (still works for that), but want to know if a general area has .dll files with locks.

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

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

    $isUsed;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top