Powershell Runspace Enter-PSSession

时间:2012-02-06 18:19:03

标签: c# powershell pipeline runspace

我正在编写一个程序,它将在远程计算机上运行程序。 我已经安装了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);**

2 个答案:

答案 0 :(得分:4)

这条线修好了。

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

答案 1 :(得分:0)

可能因为CD是别名,您可以尝试使用Set-Location(完整的CMDlet)并查看是否有帮助。我不会使用别名,因为我不确定在通过该方法创建管道时会设置什么环境。