使用PowerShell创建COM对象的实例

时间:2017-01-30 21:39:43

标签: c# powershell com cmdlets

我正在尝试在PowerShell会话中使用SAP / BusinessObjects的Universe设计工具(UDT)。

我注册了类型库:

C:\> C:\Windows\Microsoft.NET\Framework\v4.0.30319\regtlibv12.exe "C:\Program Files (x86)\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\designer.tlb

我试图直接在PowerShell中创建Designer的实例:

PS> $app = New-Object -ComObject Designer.Application
System.__ComObject

该实例没有任何预期的属性和方法:

PS> $app | get-member

   TypeName: System.__ComObject

Name                      MemberType Definition
----                      ---------- ----------
CreateObjRef              Method     System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Equals                    Method     bool Equals(System.Object obj)
GetHashCode               Method     int GetHashCode()
GetLifetimeService        Method     System.Object GetLifetimeService()
GetType                   Method     type GetType()
InitializeLifetimeService Method     System.Object InitializeLifetimeService()
ToString                  Method     string ToString()

接下来,我创建了一个C#Cmdlet,它包含了Designer的一些功能:

[System.Management.Automation.Cmdlet(System.Management.Automation.VerbsCommon.Open, "Universe")]
    [OutputType(typeof(Designer.Universe))]
    public class OpenUniverse  : System.Management.Automation.Cmdlet
    {

    Designer.Application application = null;

    [System.Management.Automation.Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
    [Alias("FullName")]
    public string[] Paths
    {
        get { return paths; }
        set { paths = value; }
    }
    private string[] paths;

    protected override void BeginProcessing()
    {
        application = new Application();
        application.Interactive = false;

        try
        {
          application.Logon("user", "password", "cluster", "secWinAd"); }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }

    } # /BeginProcessing

    protected override void ProcessRecord()
    {
        Designer.Universe universe = null;

        try
        {
            foreach (string path in Paths)
            {
                universe = application.Universes.Open(path);
                WriteObject(universe);
            }

        }
        catch (System.Runtime.InteropServices.COMException e)
        {
          # ...
        }
        finally
        {
           if ( universe != null ) { universe.Close(); }
        }

    } # /ProcessRecord

} # / OpenUniverse

在Visual Studio 2010测试中运行时,代码将返回预期的对象。

我创建了一个清单,它引用了项目创建的程序集,然后将模块导入到新的PowerShell会话中。

PS> $unv = Open-Universe 'C:\Users\XXX\AppData\Roaming\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\Universes\Foo.unv'
PS> $unv
System.__ComObject

有没有办法让PowerShell的反射生成System.__ComObject实例的属性和方法?

1 个答案:

答案 0 :(得分:0)

我不确定但是为了PowerShell可以显示实例的属性和方法(后期绑定),COM实例必须实现ITypeInfo接口。