简体   繁体   English

如何在PowerShell中使用运行空间建立和进入远程会话

[英]how to establish and enter a remote session using runspace in powershell

I am trying to establish a session with a remote host B from my machine A, within a C# code. 我正在尝试在C#代码中从我的机器A与远程主机B建立会话。 I am using runspace API for that. 我正在使用runspace API。 the code snippet is provided below 下面提供了代码段

            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            //constructing the vmname parameter here
            vmname = useralias + DateTime.Now.ToString();


            Pipeline pipeline = runspace.CreatePipeline();
            string scripttext = "$secpasswd = ConvertTo-SecureString '222_bbbb' -AsPlainText –Force";
            string scripttext1 = "$mycreds = New-object -typename System.Management.Automation.PSCredential('TS-TEST-09\\Administrator',$secpasswd)";
            string scripttext2  = "$s = New-PSSession -ComputerName TS-TEST-09 -Credential $mycreds";
            //not accepting session string here, only computername acceptable
            **string scripttext3 = "Enter-PSSession -Session $s";**



            //Command cmd = new Command(@"C:\mypath\helper.ps1", true);
            //cmd.Parameters.Add("local_useralias", useralias);
            //cmd.Parameters.Add("local_vmname", vmname);
            //cmd.Parameters.Add("local_datastore", datastoredropdown.Text.ToString());
            //cmd.Parameters.Add("local_architecture", architecturedropdown.Text.ToString());


            pipeline.Commands.AddScript(scripttext);
            pipeline.Commands.AddScript(scripttext1);
            pipeline.Commands.AddScript(scripttext2);
            pipeline.Commands.AddScript(scripttext3);
            //pipeline.Commands.Add(cmd);


            Collection<PSObject> results = pipeline.Invoke();


            runspace.Close();

this code is expected to enter into a session with machine TS-TEST-09 and invoke the script helper.ps1 existing on that machine(that part is commented out in the code currently as i am not able to enter into the session with remote host). 这个代码应该进入与机器TS-TEST-09的会话并调用该机器上存在的脚本helper.ps1(该部分在代码中被注释掉,因为我无法进入与远程主机的会话)。

now the problem is that i can't enter into the session $s using -Session parameter(highlighted at scripttext3) however i can enter into it using -Computername parameter. 现在问题是我无法使用-Session参数(在scripttext3处突出显示)进入会话$ s但是我可以使用-Co​​mputername参数进入它。

the error that i get when using -Session parameter in scripttext3 is : 在scripttext3中使用-Session参数时得到的错误是:

at invokedSystem.Management.Automation.Internal.Host.InteralHost.GetIHostSupportsInteractiveSession() at invokedSystem.Management.Automation.Internal.Host.InteralHost.GetIHostSupportsInteractiveSession()

at invokedSystem.Management.Automation. 在invokedSystem.Management.Automation。 Internal.Host.InteralHost.PushRunspace(Runspace runspace) Internal.Host.InteralHost.PushRunspace(Runspace runspace)

at Microsoft.Powershel.Commands.EnterPSSessionCommand.ProcessRecord() 在Microsoft.Powershel.Commands.EnterPSSessionCommand.ProcessRecord()

at System.Management.Automation.Cmdlet.DoProcessRecord() 在System.Management.Automation.Cmdlet.DoProcessRecord()

at System.Management.Automation.CommandProcessor.ProcessRecord() 在System.Management.Automation.CommandProcessor.ProcessRecord()

end of inner exception stack trace 内部异常堆栈跟踪的结束


does it mean i have to write a custom PSHost and add support for the Enter-PSSession cmdlet with this parameter? 这是否意味着我必须编写自定义PSHost并使用此参数添加对Enter-PSSession cmdlet的支持?

Is there any alternative to make this command work? 有没有其他方法可以使这个命令工作?

any help will be much appreciated. 任何帮助都感激不尽。

Thanks, 谢谢,

Manish 马尼什

The easiest way to open a remote session goes something like this: 打开远程会话的最简单方法是这样的:

    string shell = "http://schemas.microsoft.com/powershell/Microsoft.PowerShell";
    var target = new Uri("http://myserver/wsman");
    var secured = new SecureString();
    foreach (char letter in "mypassword")
    {
        secured.AppendChar(letter);
    }
    secured.MakeReadOnly();

    var credential = new PSCredential("username", secured);
    var connectionInfo = new WSManConnectionInfo(target, shell, credential);

    Runspace remote = RunspaceFactory.CreateRunspace(connectionInfo);
    remote.Open();

    using (var ps = PowerShell.Create())
    {
        ps.Runspace = remote;
        ps.Commands.AddCommand("'This is running on {0}.' -f (hostname)");

        Collection<PSObject> output = ps.Invoke();
    }

You could also create remote pipelines from the remote runspace instance, but the new PowerShell object is a much more managable way to do this (since powershell v2.) 您还可以从远程运行空间实例创建远程管道,但新的PowerShell对象是一种更易于管理的方法(因为PowerShell v2。)

In powershell v3, you can just new up a WSManConnectionInfo and set the ComputerName property as the other properties adopt the same defaults as the above. 在powershell v3中,您可以只创建一个WSManConnectionInfo并设置ComputerName属性,因为其他属性采用与上面相同的默认值。 Unfortunately these properties are read-only in v2 and you have to pass in the minimum as above. 不幸的是,这些属性在v2中是只读的,你必须传递最小值,如上所述。 Other variants of the constructor will let you use kerberos/negotiate/credssp etc for authentication. 构造函数的其他变体将允许您使用kerberos / negotiate / credssp等进行身份验证。

-Oisin -Oisin

I wanted to leave a comment on the solution, as it helped me alot as well, 我想对解决方案发表评论,因为它对我有很多帮助,

but one thing i was missing was the port for WSMan which is 5985 但我遗漏的一件事是WSMan的端口是5985

so this var target = new Uri(" http://myserver/wsman "); 所以这个var target = new Uri(“ http:// myserver / wsman ”); should be var target = new Uri(" http://myserver:5895/wsman "); 应该是var target = new Uri(“ http:// myserver:5895 / wsman ”); in my case 在我的情况下

Have you tried Invoke-Command ? 你试过Invoke-Command吗? Enter-PsSession is there for interactive use. Enter-PsSession可供交互使用。 (see help Enter-PsSession -online ). (请参阅help Enter-PsSession -online )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM