Running command on remote windows using winrm in c #

I have an easy way to connect to a remote Windows machine from a local Windows machine using winrm. Here is the actual powershell code:

Set-Item WSMan:\localhost\Client\TrustedHosts -Value $ip -Force
$securePassword = ConvertTo-SecureString -AsPlainText -Force 'mypass'
$cred = New-Object System.Management.Automation.PSCredential 'Administrator', $securePassword
$cmd = {ls C:\temp}
Invoke-Command -ComputerName $ip -Credential $cred -ScriptBlock $cmd

      

I want to figure out how to do the exact thing in C #.

Also, it would be helpful if someone can tell me if there is a way to send files to C # winrm.

Note. This is only the C # code needed on my local machine. The remote computer is already configured.

+3


source to share


2 answers


Well, I figured out one way as I post below, but while it works fine on Windows 8, it encounters the "Strong name validation" error on Windows 7, so I must keep looking into that. However, please feel free to post other ideas.

-> add System.Management.Automation.dll to your project.



    WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
    connectionInfo.ComputerName = host;
    SecureString securePwd = new SecureString();
    pass.ToCharArray().ToList().ForEach(p => securePwd.AppendChar(p));
    connectionInfo.Credential = new PSCredential(username, securePwd);
    Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
    runspace.Open();
    Collection<PSObject> results = null;
    using (PowerShell ps = PowerShell.Create())
    {
        ps.Runspace = runspace;
        ps.AddScript(cmd);
        results = ps.Invoke();
        // Do something with result ... 
    }
    runspace.Close();

    foreach (var result in results)
    {
        txtOutput.AppendText(result.ToString() + "\r\n");
    }

      

+5


source


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

The code is in one file if you just want to copy it, as well as the NuGet package that includes a reference to System.Management.Automation.

It automatically manages trusted hosts, can run script blocks, and also upload files (which are not actually supported, but I created a job). Returns are always original Powershell objects.



// 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 protocol!).
var localFilePath = @"D:\Temp\BigFileLocal.nupkg";
var fileBytes = File.ReadAllBytes(localFilePath);
var remoteFilePath = @"D:\Temp\BigFileRemote.nupkg";
machineManager.SendFile(remoteFilePath, fileBytes);

      

Please flag as an answer if it helps. I've been using this for a while with my automated deployments. If you find problems, please leave comments.

+3


source







All Articles