2010-09-22 15 views
13

我想創建一個小應用程序,它可以使用WinRM而不是WMI收集系統信息(Win32_blablabla)。我如何從C#做到這一點?如何訪問C#中的WinRM

主要目標是使用WS-Man(WinRm)而不是DCOM(WMI)。

回答

13

我想最簡單的方法是使用WSMAN自動化。從WINDWOS參考wsmauto.dll \ SYSTEM32在您的項目:

alt text

那麼,下面的代碼應該爲你工作。 API的描述是在這裏: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); 
    } 
} 

希望這會有所幫助,至於

1

我想指出,這表明在默認情況下在Visual Studio 2010
C.F.的互操作錯誤http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx

似乎有兩種方法可以解決這個問題。這首先記錄在上面列出的文章中,似乎是解決問題的正確方法。此示例的相關更改如下:

WSMan wsManObject = new WSMan(); 這是代替IWSMan wsman = new WSManClass();這會拋出錯誤。

第二種解決方法是進入VS2010-> Solution Explorer-> Solution-> Project-> References並選擇WSManAutomation。右鍵單擊或按Alt-Enter訪問屬性。更改wsmauto引用的「Embed Interop Types」屬性的值。

3

我有一篇文章介紹了通過WinRM從.NET運行PowerShell的簡單方法,網址爲http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/

如果您想複製它,它的代碼位於單個文件中,它也是一個NuGet包,其中包含對System.Management.Automation的引用。它自動管理可信主機,可以運行腳本塊,併發送文件(這不是真的支持,但我創建了一個工作)。返回始終是Powershell的原始對象。

// this is the entrypoint to interact with the system (interfaced for testing). 
var machineManager = new MachineManager(
    "10.0.0.1", 
    "Administrator", 
    MachineManager.ConvertStringToSecureString("xxx"), 
    true); 

// will perform a user initiated reboot. 
machineManager.Reboot(); 

// can run random script blocks WITH parameters. 
var fileObjects = machineManager.RunScript(
    "{ param($path) ls $path }", 
    new[] { @"C:\PathToList" }); 

// can transfer files to the remote server (over WinRM's protocol!). 
var localFilePath = @"D:\Temp\BigFileLocal.nupkg"; 
var fileBytes = File.ReadAllBytes(localFilePath); 
var remoteFilePath = @"D:\Temp\BigFileRemote.nupkg"; 
machineManager.SendFile(remoteFilePath, fileBytes); 

希望這可以幫助,我一直在使用這一段時間與我的自動化部署。如果您發現問題,請留下評論。