Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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();
Posted
Updated 29-Nov-16 2:11am
v2
Comments
Richard MacCutchan 25-Nov-16 3:40am    
The error message is telling you what to investigate, nothing to do with your code.
Member 12586674 25-Nov-16 4:31am    
What exactly I need to do. Do I need to change settings/disable the firewall on the server?
I tried to change the "Trusted Host" setting but its not working.
Richard MacCutchan 25-Nov-16 4:34am    
I have no idea what the setup is between your two systems so I cannot even guess. You need to find out why the connection is being blocked.

1 solution

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900