Search code examples
c#powershellcomcom-object

How does powershell process return types/objects from an externally loaded DLL?


I am a novice programmer in .NET and Powershell,

I have a small compiled .NET DLL that utilizes the Directory Services and TSUserExLib for fetching TerminalService attributes. The DLL has a one static function that returns "IADsTSUserEx". I tested the DLL and it works when returning a string, but is it possible to return the IADsTSUserEx class\object type to powershell? When I execute the static function from powershell I get nothing back, not even null. I tried it using the following commands

Add-Type -Path "c:\temp\test.dll"
[ABC.Class1]::getTSEntry("user@domain.com")

The DLL contains this code snippet:

DirectoryEntry user = result.GetDirectoryEntry();
                IADsTSUserEx tsuser = (IADsTSUserEx)result.GetDirectoryEntry().NativeObject;
                return tsuser;

Solution

  • Since your method returns a COM object and PowerShell isn't directly exposing its methods and properties to you, you'll need to access them with reflection and the Type.InvokeMember method:

    $entry = [ABC.Class1]::getTSEntry("user@domain.com");
    $entryType = $entry.GetType();
    $binder = $null;
    $someMethodParameters = @('Parameter #1', 12345, 'Parameter #3');
    $someMethodResult = $entryType.InvokeMember('SomeMethod', 'Public, Instance, InvokeMethod', $binder, $entry, $someMethodParameters);
    $somePropertyValue = $entryType.InvokeMember('SomeProperty', 'Public, Instance, GetProperty', $binder, $entry, $null);