2

我想从 PowerShell 枚举当前进程中的所有 AppDomain。该过程恰好是托管StudioShell的 Visual Studio 。为此,我需要实例化 CorRuntimHost,它是 mscoree.tlb 的一部分,因此我可以调整此 C# 代码..

我试图获取 CorRunTimeHost 的正确名称并将其传递给New-Object -COMObject"objectName"。根据这个论坛发帖,我搜索了注册表,我认为正确的名称是CLRMetaData.CorRuntimeHost。但是,虽然New-Object -ComObject 'CLRMetaData.CorRuntimeHost' -Strict确实返回了一个对象,但它只公开了 COM 对象的固有方法。

基于这个stackoverflow问题,我尝试了[Activator]::CreateInstance()。但是,以下两条语句给我带来了与 New-Object 相同的问题,即我无法调用ICorRuntimeHost::EnumDomains()方法。

$corRuntimeHost = [Activator]::CreateInstance([Type]::GetTypeFromProgID('CLRMetaData.CorRuntimeHost'));
$enumerator = $null;
$corRuntimeHost.EnumDomains([ref]$enumerator);

Method invocation failed because [System.__ComObject] doesn't contain a method named 'EnumDomains'.
At line:1 char:1
+ $corRuntimeHost.EnumDomains([ref]$enumerator)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
4

1 回答 1

2

为了让它在 PowerShell 3.0 中工作,我最终不得不使用AssemblyBuilder。下面是工作代码:

问题似乎是 .NET 4.0 中没有mscoree.CorRuntimeHostClass的公共构造函数,但 3.5 中有。

我后来在带有 powershell 2.0 的 Windows 7 VM 上对此进行了测试,现在这段代码将在 PowerShell 2.0 和 3.0 中运行。

$tlbName = Split-Path -Parent ([AppDomain]::CurrentDomain.GetAssemblies() | Where { $_.Location -Match '\\mscorlib.dll$' }).Location 
$tlbName = Join-Path $tlbName 'mscoree.tlb';

$csharpString = @"
//adapted from here http://blog.semanticsworks.com/2008/04/enumerating-appdomains.html
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;

public class ListProcessAppDomains
{

    [DllImport( `"oleaut32.dll`", CharSet = CharSet.Unicode, PreserveSig = false )]
    private static extern void LoadTypeLibEx
        (String strTypeLibName, RegKind regKind, 
         [MarshalAs( UnmanagedType.Interface )] out Object typeLib);

    private enum RegKind
    {
        Default = 0,
        Register = 1,
        None = 2
    }

    private class ConversionEventHandler : ITypeLibImporterNotifySink
    {
        public void ReportEvent( ImporterEventKind eventKind, int eventCode, string eventMsg )
        {
            Console.Error.WriteLine("Kind: {0} Code: {1} Message");
        }

        public Assembly ResolveRef( object typeLib )
        {
            string stackTrace = System.Environment.StackTrace;
            Console.WriteLine("ResolveRef ({0})", typeLib);
            Console.WriteLine(stackTrace);
          return null; 
        }    
    }

    public static AssemblyBuilder LoadMsCoreeDll( ref Object typeLib ) {
        ConversionEventHandler eventHandler = new ConversionEventHandler();
        string assemblyName = "PoshComWrapper.dll";
        LoadTypeLibEx( @"$($tlbName)", RegKind.None, out typeLib ); 
        TypeLibConverter typeLibConverter = new TypeLibConverter();
        return typeLibConverter.ConvertTypeLibToAssembly( typeLib, assemblyName, 0, eventHandler, null, null, null, null );
    }
}
"@

# So we can run this scipt multiple times
try { [ListProcessAppDomains] } catch {  Add-Type -TypeDefinition $csharpString }

function Get-AppDomain {
    $typeLib = $null;
    $assemblyBuilder = [ListProcessAppDomains]::LoadMsCoreeDll([ref] $typeLib)
    $corRuntimeHostClass = $assemblyBuilder.CreateInstance('PoshComWrapper.CorRuntimeHostClass')
    $enumHandle = [IntPtr]::Zero
    $corRuntimeHostClass.EnumDomains([ref] $enumHandle);
    $appDomain = $null;
    do
    {
        $corRuntimeHostClass.NextDomain($enumHandle, [ref] $appDomain);
        if ($appDomain -ne $null -and $appDomain.GetType() -eq [AppDomain]) { $appDomain; }
    } while ($appDomain -ne $null)
}

Get-AppDomain 
于 2013-05-23T01:02:57.200 回答