Powershell运行空间进入PSSession



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

由于CD是一个Alias,您可以尝试使用Set Location(完整的CMDlet),看看这是否有帮助。我会错误地不使用别名,因为我不确定通过该方法创建管道时会设置什么环境。

最新更新