5

我有一种简单的方法可以使用 winrm 从本地 Windows 机器连接到远程 Windows 机器。这是正在运行的powershell代码:

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

我想弄清楚如何在 c# 中做确切的事情。

另外,如果有人告诉我是否有在 c# winrm 中发送文件的方法,那将会很有帮助。

注意:这是我本地机器上唯一需要的 ac# 代码。远程机器已经设置好了。

4

2 回答 2

6

好吧,我想出了一种方法,我将在下面发布,但是虽然它在 Windows 8 上运行良好,但在 Windows 7 上遇到错误“强名称验证失败”,所以我应该继续研究这个。仍然请随时发表其他想法。

--> 将 System.Management.Automation.dll 添加到您的项目中。

    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");
    }
于 2014-12-01T04:38:48.443 回答
3

我在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);

如果这有帮助,请标记为答案。我已经在我的自动化部署中使用了一段时间。如果您发现问题,请发表评论。

于 2015-07-10T17:45:43.110 回答