Search code examples
c#powershellcom-interopcomobject

Accessing Powershell COM Object in C#?


I need to convert a Powershell script to C#.

The Powershell script accesses the Windows Deployment Service COM Object:

$wdsObject = New-Object -ComObject WdsMgmt.WdsManager
$wdsServer = $wdsObject.getWdsServer("Localhost")
[...]

Is it possible to access these COM Objects in C#?

I couldn't find the corresponding COM Object reference in Visual C#. I tried to add the wdsmgmt.dll from System32 as a reference in a C# project, but that didn't work. I'm quite stumped otherwise.

EDIT:

Answer to comment 1: Best way to access COM objects from C#

The COM Object in question isn't listed in the references. I've looked through the list about 5 times to be sure I wouldn't miss it. Would there be a way to make that COM Object show up in the COM references list in C#?

Answer to comment 2 (what did not work): Trying to add wdsmgmt.dll shows the following error:

Please make sure the file is accessible, and that it is a valid assembly or COM component.

The file is accessible, but it doesn't seem to be a valid COM component in the eyes of C#.

A search in the registry for WdsMgmt shows that the COM Object is at least somehow present:

HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{CD583E47-B079-4025-A799-5F951D016D3E}

Maybe the rephrased question would be:

How do I add a COM Object reference to C# when I know it's name in Powershell?


Solution

  • You can directly mirror what PowerShell does by using dynamic, and creating the instance by ProgId. See https://stackoverflow.com/a/3251325/8446 for example.