mary
mary

Reputation: 29

Remote connect to powershell from C#

I want to remote connect powershell from windows 7 to windows server 2008 R2 (that's installed in VMware) with ASP.NET.

This is my code :

    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();

but in runSpace.open() sometimes give this error

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

and sometimes this error:

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.

I read about_Remote_Troubleshooting but I can't see why these errors occur. Can anyone help me?

Upvotes: 2

Views: 8730

Answers (1)

Juan Ayala
Juan Ayala

Reputation: 3518

Ok so you said that both machines are on the SAME domain, but I see you are trying to use the local admin account. That may be an issue but not necessarily. To replicate this, I set up Win2k8R2 on a VM and followed the following steps:

Steps #1&2 apply to Server 2008 R2 Core Install. If you have the full install, just skip to #3.

  1. Run following commands to Install .NET2 & PowerShell (within cmd.exe)
    • DISM /Online /Enable-Feature /Featurename:NetFx2-ServerCore
    • DISM /Online /Enable-Feature /FeatureName:MicrosoftWindowsPowerShell
  2. Install some useful PS CmdLets (within cmd.exe)
    • DISM /online /enable-feature /featurename=ServerManager-PSH-Cmdlets
    • DISM /online /enable-feature /featurename=BestPractices-PSH-Cmdlets
  3. Enable Remote Shell (within powershell.exe)
    • Set-Excutionpolicy RemoteSigend
    • Configure-SMRemoting.ps1 -force -enable

And then I took your sample code, I didn't really make any substantial changes to it

        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();

I did add a dll reference to C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll just in case its not what you are using.

And then it worked. So my feeling is that its not your code but either your credentials, or the remote setup on the target machine.

Upvotes: 1

Related Questions