How to access WinRM in C#

后端 未结 3 1374
一整个雨季
一整个雨季 2021-01-01 17:48

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 18:08

    I've got an article that describes an easy way to run Powershell through WinRM from .NET at http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/.

    The code is in a single file if you want to just copy it and it's also a NuGet package that includes the reference to System.Management.Automation.

    It auto manages trusted hosts, can run script blocks, and also send files (which isn't really supported but I created a work around). The returns are always the raw objects from 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);
    

    Hope this helps, I've been using this for a while with my automated deployments. Please leave comments if you find issues.

提交回复
热议问题