4

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

程序编译并运行,但在 answer 变量中显示:“方法或操作未实现。\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);**
4

2 回答 2

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);
于 2012-02-07T15:21:58.613 回答
0

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

于 2012-02-06T18:56:00.567 回答