Question

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?

Was it helpful?

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.

OTHER TIPS

Have you tried using TlbImp?

Creating a COM Class Wrapper

For C# code to reference COM objects and interfaces, you need to include a .NET Framework definition for the COM interfaces in your C# build. The easiest way to do this is to use TlbImp.exe (Type Library Importer), a command-line tool included in the .NET Framework SDK. TlbImp converts a COM type library into .NET Framework metadata — effectively creating a managed wrapper that can be called from any managed language. .NET Framework metadata created with TlbImp can be included in a C# build via the /R compiler option. If you are using the Visual Studio development environment, you only need to add a reference to the COM type library and the conversion is done for you automatically.

Here is more information about this interop tool:

Tlbimp.exe (Type Library Importer)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top