[英]Powershell Runspace Enter-PSSession
我正在編寫一個程序,它將在遠程計算機上運行程序。 我已經安裝了windows sdk並且已成功上傳了我的文件,現在我想遠程運行更改目錄並使用power shell執行命令。
程序編譯並運行但在答案變量中它表示: “方法或操作未實現。\\ 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是別名,您可以嘗試使用Set-Location(完整的CMDlet)並查看是否有幫助。 我不會使用別名,因為我不確定在通過該方法創建管道時會設置什么環境。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.