gpt4 book ai didi

c# - Powershell Runspace 进入PSSession

转载 作者:太空狗 更新时间:2023-10-30 01:24:29 25 4
gpt4 key购买 nike

我正在编写一个程序,它将在远程机器上运行一个程序。我已经安装了 windows sdk 并成功上传了我的文件现在我想远程运行更改目录并使用执行命令电源外壳。

程序编译并运行,但在答案变量中显示:“方法或操作未实现。\r\n”

// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript("Enter-PSSession " + host + Environment.NewLine + "cd " + uploadtodir + Environment.NewLine + command + Environment.NewLine + "exit" + Environment.NewLine + "exit" + Environment.NewLine);
// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns. For example, the script
// "Get-Process" returns a collection of System.Diagnostics.Process instances.

pipeline.Commands.Add("Out-String");
// execute the script

Collection<PSObject> results = new Collection<PSObject>();
try
{
results = pipeline.Invoke();
}

catch (Exception ex)
{
results.Add(new PSObject((object)ex.Message));
}

// close the runspace
runspace.Close();
// convert the script result into a single string

StringBuilder stringBuilder = new StringBuilder();

foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}

string answer = stringBuilder.ToString();

我尝试在管道中使用另一个命令,但它也失败了,但没有错误输出。

**pipeline.Commands.AddScript("$sessions = New-PSSession -ComputerName " + host + Environment.NewLine + "Invoke-Command -session $sessions -ScriptBlock {cd " + uploadtodir+"}" + Environment.NewLine+"Invoke-Command -session $sessions -ScriptBlock {"+command+ "}" + Environment.NewLine + "Remove-PSSession -Session $sessions" + Environment.NewLine + "exit" + Environment.NewLine + "exit" + Environment.NewLine);**

最佳答案

这一行修复了它。

pipeline.Commands.AddScript("$sessions = New-PSSession -ComputerName " + host + Environment.NewLine 
+ "Invoke-Command -session $sessions -ScriptBlock {cd " + uploadtodir+"}" + Environment.NewLine
+"Invoke-Command -session $sessions -ScriptBlock {"+command+ "}" + Environment.NewLine
+ "Remove-PSSession -Session $sessions" + Environment.NewLine
+ "exit" + Environment.NewLine + "exit" + Environment.NewLine);

关于c# - Powershell Runspace 进入PSSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9165088/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com