How to access WinRM in C#

Mark picture Mark · Sep 22, 2010 · Viewed 10.6k times · Source

I'd like to create a small application that can collect system information (Win32_blablabla) using WinRM as opposed to WMI. How can i do that from C#?

The main goal is to use WS-Man (WinRm) as opposed to DCOM (WMI).

Answer

serge_gubenko picture serge_gubenko · Nov 11, 2010

I guess the easiest way would be to use WSMAN automation. Reference wsmauto.dll from windwos\system32 in your project:

alt text

then, code below should work for you. API description is here: msdn: WinRM C++ API

IWSMan wsman = new WSManClass();
IWSManConnectionOptions options = (IWSManConnectionOptions)wsman.CreateConnectionOptions();                
if (options != null)
{
    try
    {
        // options.UserName = ???;  
        // options.Password = ???;  
        IWSManSession session = (IWSManSession)wsman.CreateSession("http://<your_server_name>/wsman", 0, options);
        if (session != null)
        {
            try
            {
                // retrieve the Win32_Service xml representation
                var reply = session.Get("http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service?Name=winmgmt", 0);
                // parse xml and dump service name and description
                var doc = new XmlDocument();
                doc.LoadXml(reply);
                foreach (var elementName in new string[] { "p:Caption", "p:Description" })
                {
                    var node = doc.GetElementsByTagName(elementName)[0];
                    if (node != null) Console.WriteLine(node.InnerText);
                }
            }
            finally
            {
                Marshal.ReleaseComObject(session);
            }
        }
    }
    finally
    {
        Marshal.ReleaseComObject(options);
    }
}

hope this helps, regards