使用C#连接到PowerShell时出错 [英] Error while connecting to powershell using C#

查看:80
本文介绍了使用C#连接到PowerShell时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#连接到powershell。但是在连接时我在尝试打开运行空间时遇到以下错误。



连接到远程服务器失败,并显示以下错误消息:WinRM客户端无法完成指定时间内的操作。检查机器名称是否有效并且是否可以通过网络访问,并且启用了Windows远程管理服务的防火墙例外。



下面是我的代码。



我尝试了什么:



I'm trying to connect to powershell using C#. But while connectting I'm getting the following error when trying to open the runspace.

"Connecting to remote server failed with the following error message : The WinRM client cannot complete the operation within the time specified. Check if the machine name is valid and is reachable over the network and firewall exception for Windows Remote Management service is enabled."

Below is my code.

What I have tried:

string shellUri = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
            PSCredential remoteCredential = new PSCredential("Username", StringToSecureString("Password"));
            WSManConnectionInfo connectionInfo = new WSManConnectionInfo(false, "Server IP", 5985, "/wsman", shellUri, remoteCredential);

            Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);

            runspace.Open();

            Pipeline pipeline = runspace.CreatePipeline();

            Command newMailBox = new Command("New-Mailbox");

            newMailBox.Parameters.Add("Name", "TestName1");
            newMailBox.Parameters.Add("Alias", "TestName1");
            newMailBox.Parameters.Add("database", "Mailbox Database 1406738839");
            newMailBox.Parameters.Add("DisplayName", "TestName1");
            newMailBox.Parameters.Add("UserPrincipalName", "TestName1@test.com");
            newMailBox.Parameters.Add("OrganizationalUnit", "ou=myorg,dc=ad,dc=lab");
            newMailBox.Parameters.Add("FirstName", "TestName1");

            pipeline.Commands.Add(newMailBox);

            Collection<psobject> result = pipeline.Invoke();

推荐答案

如评论中所述,错误似乎不是您的代码的问题而是阻碍沟通的东西。也许服务器IP错误,或端口,或凭据或您有防火墙问题。你必须全力以赴才能弄明白。
As stated in the comments, the error does not appear to be an issue with your code but rather something blocking the communication. Perhaps the server ip is wrong, or the port, or the credentials or you have a firewall issue. You'll have to work through it all to figure it out on your end.


这篇关于使用C#连接到PowerShell时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆