c# - 使用 PowerShell 中的 WinRM 连接到远程服务器失败

标签 c# powershell winrm

我正在尝试从我的计算机运行 powershell 代码到我计算机上的 vm,但我不断收到此错误:

Connecting to remote server failed with the following error message : The WinRM client cannot process the request. If the authentication scheme is different from Kerberos, or if the client computer is not joined to a domain, then HTTPS transport must be used or the destination machine must be added to the TrustedHosts configuration setting. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. You can get more information about that by running the following command: winrm help config. For more information, see the about_Remote_Troubleshooting Help topic.

我的代码:

  string runasUsername = @"\aaa";
    string runasPassword = "aaa";
    SecureString ssRunasPassword = new SecureString();
    foreach (char x in runasPassword)
        ssRunasPassword.AppendChar(x);
    PSCredential credentials = new PSCredential(runasUsername, ssRunasPassword);

    var connInfo = new WSManConnectionInfo(new Uri("http://10.0.5.35/PowerShell"),
        "http://schemas.microsoft.com/powershell/Microsoft.Exchange",credentials);
    connInfo.AuthenticationMechanism = AuthenticationMechanism.Basic;

    var runspace = RunspaceFactory.CreateRunspace(connInfo);


    var domainName = "domainName.COM";
    var password = "ActiveDirectoryPassword1234";
    var ssPassword = new SecureString();
    foreach (char c in password)
        ssPassword.AppendChar(c);


    var command = new Command("New-Mailbox");

    command.Parameters.Add("FirstName", firstName);
    command.Parameters.Add("LastName", lastName);
    command.Parameters.Add("Password", ssPassword);
    command.Parameters.Add("ResetPasswordOnNextLogon", false);
    command.Parameters.Add("OrganizationalUnit", "NeumontStudents");

    runspace.Open(); <--//error here
    var pipeline = runspace.CreatePipeline();
    pipeline.Commands.Add(command);


    var results = pipeline.Invoke();

    runspace.Dispose();

我错过了什么?

最佳答案

如果客户端和远程计算机不在同一个域,您有以下两种选择之一:

  • 使用 HTTPS 作为传输协议(protocol)
  • 将远程机器添加到客户端的可信主机列表中

为了configure WinRM要使用 HTTPS,请在两台机器上以管理员身份打开 PowerShell 控制台并运行:

winrm quickconfig -transport:https

在防火墙上打开5986端口:

netsh firewall add portopening TCP 5986 "WinRM over HTTPS"

或者,您可以在客户端通过运行以下命令将远程计算机添加为受信任的主机:

winrm set winrm/config/client @{TrustedHosts="10.0.5.35"}

关于c# - 使用 PowerShell 中的 WinRM 连接到远程服务器失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16010091/

相关文章:

c# - 为什么代码会产生 ObjectDisposeException

c# - 在 C# 中使用 Powershell 远程调用的内存泄漏

xml - 如何防止XmlDocument.Save编写新元素的 namespace ?

c# - 使用 PowerShell 和模块化 GUI 吗?

security - Ansible,Windows - 如何访问网络文件夹?

java - 在 URL 上的 Conduit 上检测到 Winrm4j 授权循环,领域为 "null"

c# - 如何在 C# 中将数字拆分为单个数字?

c# - C#中的一次性单例

windows-7 - 将跳转列表快捷方式复制到磁盘

windows - 使用 Chef Knife winrm 将文件传输到远程 Windows 机器