c# - 从 C# 远程连接到 powershell

标签 c# powershell

我想使用 ASP.NET 将 powershell 从 Windows 7 远程连接到 Windows Server 2008 R2(安装在 VMware 中)。

这是我的代码:

    string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
    var target = new Uri("http://win-qkheb9s51i8/wsman");

    Pipeline p = runSpace.CreatePipeline();
    SecureString passing = new SecureString();
    string password = "A123456a";

    foreach (char c in password)
    {
        passing.AppendChar(c);
    }
    passing.MakeReadOnly();

    var cred = new PSCredential(@"win-qkheb9s51i8\Administrator", passing);

    var connectionInfo = new WSManConnectionInfo(target, shell, cred);
    connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
    connectionInfo.OpenTimeout = 1 * 60 * 1000;
   runSpace = RunspaceFactory.CreateRunspace(connectionInfo);
   runSpace.Open();

但是在runSpace.open()中有时会报这个错

Connecting to remote server failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.

有时这个错误:

ERROR: The client cannot connect to the destination specified in the request. Verify that the service on the destination is running and is accepting requests.

我阅读了 about_Remote_Troubleshooting 但我不明白为什么会出现这些错误。谁能帮帮我?

最佳答案

好吧,你说两台机器都在同一个域中,但我看到你正在尝试使用本地管理员帐户。这可能是一个问题,但不一定。为了复制这个,我在 VM 上设置了 Win2k8R2 并按照以下步骤操作:

第 1 步和第 2 步适用于 Server 2008 R2 核心安装。如果您有完整安装,请跳至#3。

  1. 运行以下命令以安装 .NET2 和 PowerShell(在 cmd.exe 中)
    • DISM/Online/Enable-Feature/Featurename:NetFx2-ServerCore
    • DISM/Online/Enable-Feature/FeatureName:MicrosoftWindowsPowerShell
  2. 安装一些有用的 PS CmdLets(在 cmd.exe 中)
    • DISM/online/enable-feature/featurename=ServerManager-PSH-Cmdlets
    • DISM/online/enable-feature/featurename=BestPractices-PSH-Cmdlets
  3. 启用远程 Shell(在 powershell.exe 中)
    • 设置执行策略 RemoteSigend
    • Configure-SMRemoting.ps1 -force -enable

然后我拿了你的示例代码,我并没有对它做任何实质性的改动

        Console.Write("Target: ");
        var target = Console.ReadLine();
        Console.Write("User: ");
        var user = Console.ReadLine();
        user = string.Format("{0}\\{1}", target, user);
        string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
        var targetWsMan = new Uri(string.Format("http://{0}:5985/wsman", target));

        using (var passing = new SecureString())
        {
            Console.Write("Password: ");
            var cki = default(ConsoleKeyInfo);
            do
            {
                cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.Enter)
                    Console.Write(cki.KeyChar);
                else
                    passing.AppendChar(cki.KeyChar);
            }
            while (cki.Key != ConsoleKey.Enter);
            passing.MakeReadOnly();

            var cred = new PSCredential(user, passing);

            var connectionInfo = new WSManConnectionInfo(targetWsMan, shell, cred);
            connectionInfo.OperationTimeout = 4 * 60 * 1000; // 4 minutes.
            connectionInfo.OpenTimeout = 1 * 60 * 1000;
            using (var runSpace = RunspaceFactory.CreateRunspace(connectionInfo))
            {
                var p = runSpace.CreatePipeline();
                runSpace.Open();
                Console.WriteLine("Connected to {0}", targetWsMan);
                Console.WriteLine("As {0}", user);
                Console.Write("Command to run: ");
                var cmd = Console.ReadLine();
                p.Commands.Add(cmd);
                var returnValue = p.Invoke();
                foreach (var v in returnValue)
                    Console.WriteLine(v.ToString());
            }
        }

        Console.WriteLine("End...");
        Console.ReadLine();

我确实添加了对 C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll 的 dll 引用,以防万一它不是您使用的.

然后就成功了。所以我的感觉是,这不是您的代码,而是您的凭据或目标机器上的远程设置。

关于c# - 从 C# 远程连接到 powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11969621/

相关文章:

c# - 向文件添加新的元数据属性

azure - "Get-InstalledModule -name az "命令给出 'No result Found' “但是所有 Az 命令都有效

c# - 使用 ImpromptuInterface 调用基类的私有(private)成员

c# - 无法找到 testhost.dll。请发布您的测试项目并重试

c# - 如何从列表框 C# 中删除选定的项目

powershell - 在 PowerShell 中从文件名中删除路径和扩展名

使用 send-mailmessage 命令时的电子邮件凭据

c# - 如何拆分字符串然后重新加入它?

c# - 使用 C#,LINQ 如何一次又一次地在标记之间选择项目?

regex - Powershell Get-Content -> Foreach-Object -> -replace -> Out-File 在每个文件的开头添加一个字符 (0x00)