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

发布于 2024-12-27 11:17:51 字数 2457 浏览 1 评论 0原文

我正在尝试使用 C# 代码从我的计算机 A 与远程主机 B 建立会话。我正在为此使用运行空间 API。下面提供了代码片段,

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

此代码预计会进入与机器 TS-TEST-09 的会话,并调用该机器上现有的脚本 helper.ps1(该部分在当前代码中被注释掉,因为我无法输入进入与远程主机的会话)。

现在的问题是我无法使用 -Session 参数(在 scripttext3 中突出显示)进入会话 $s,但是我可以使用 -Computername 参数进入它。

在 scripttext3 中使用 -Session 参数时出现的错误是:

在 调用System.Management.Automation.Internal.Host.InteralHost.GetIHostSupportsInteractiveSession()

位于调用的System.Management.Automation。 Internal.Host.InteralHost.PushRunspace(Runspace运行空间)

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

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

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

内部异常堆栈跟踪结束


是否意味着我必须编写自定义 PSHost 并使用此参数添加对 Enter-PSSession cmdlet 的支持?

有没有其他方法可以使该命令起作用?

任何帮助将不胜感激。

谢谢,

曼尼什

I am trying to establish a session with a remote host B from my machine A, within a C# code. I am using runspace API for that. 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).

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.

the error that i get when using -Session parameter in scripttext3 is :

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

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

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

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

at 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?

Is there any alternative to make this command work?

any help will be much appreciated.

Thanks,

Manish

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

も星光 2025-01-03 11:17:51

打开远程会话的最简单方法如下:

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

您还可以从远程运行空间实例创建远程管道,但新的 PowerShell 对象是一种更易于管理的方法(自 powershell v2 以来) .)

在 powershell v3 中,您只需新建一个 WSManConnectionInfo 并设置 ComputerName 属性,因为其他属性采用与上述相同的默认值。不幸的是,这些属性在 v2 中是只读的,您必须如上所述传递最小值。构造函数的其他变体将允许您使用 kerberos/negotiate/credssp 等进行身份验证。

-奥辛

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.)

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. Unfortunately these properties are read-only in v2 and you have to pass in the minimum as above. Other variants of the constructor will let you use kerberos/negotiate/credssp etc for authentication.

-Oisin

婴鹅 2025-01-03 11:17:51

我想对该解决方案发表评论,因为它也对我有很大帮助,

但我缺少的一件事是 WSMan 的端口是 5985

所以这个
var target = new Uri("http://myserver/wsman");
应该是
var target = new Uri("http://myserver:5895/wsman");
就我而言

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

so this
var target = new Uri("http://myserver/wsman");
should be
var target = new Uri("http://myserver:5895/wsman");
in my case

萌梦深 2025-01-03 11:17:51

您尝试过Invoke-Command吗? Enter-PsSession 用于交互式使用。 (请参阅help Enter-PsSession -online)。

Have you tried Invoke-Command? Enter-PsSession is there for interactive use. (see help Enter-PsSession -online).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文