如何在C#中访问WinRM

Mar*_*ark 17 c# windows wmi remote-management

我想创建一个可以使用WinRM而不是WMI收集系统信息(Win32_blablabla)的小应用程序.我怎么能用C#做到这一点?

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

ser*_*nko 14

我想最简单的方法是使用WSMAN自动化.在项目中引用windwos\system32中的wsmauto.dll:

替代文字

那么,下面的代码应该适合你.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这有帮助,问候


wls*_*ill 6

我在http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/ 上有一篇文章描述了一种通过 WinRM 从 .NET 运行 Powershell 的简单方法。

如果您只想复制代码,则代码位于单个文件中,它也是一个 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);
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助,我已经在我的自动化部署中使用了一段时间。如果您发现问题,请发表评论。