public PSResult InokePipeline(string command) { Pipeline pipeline = shellrunspace.CreatePipeline(); PSResult result = new PSResult(); try { pipeline.Commands.AddScript(command); result.Result = pipeline.Invoke(); } catch (Exception e) { result.Error = "Exception thrown running command: " + command + Environment.NewLine + "With the exception: " + e.Message; } return(result); }
/// /// Invoke a script and return a string. /// Automatically adds Out-String in the Cmdlet pipeline to ensure the end result is a string. /// The runspace key is used to select the runspace pool for the requests. /// The request Id is used to associate a request with an Id and is used for cancellation. /// public async Task <object> InvokeScriptAsString(object input) { var inputDict = input as IDictionary <string, object>; if (inputDict == null) { throw new ArgumentException("input"); } string runspaceKey = inputDict["RunspaceKey"] as string; string requestId = inputDict["RequestId"] as string; string script = inputDict["Script"] as string; if (string.IsNullOrEmpty(runspaceKey)) { Console.WriteLine("Null Runspace Key"); throw new ArgumentNullException("runspaceKey"); } if (string.IsNullOrEmpty(requestId)) { Console.WriteLine("Null requestId"); throw new ArgumentNullException("requestId"); } RunspacePool rsPool; if (!runspacePools.TryGetValue(runspaceKey, out rsPool)) { Console.WriteLine("Runspace pool not created."); throw new InvalidOperationException("Runspace pool not created for " + runspaceKey); } var powerShell = PowerShell.Create(); powerShell.RunspacePool = rsPool; // Wrap the original startup script and inject it as a variable in the runspace. // This startup script is then automatically invoked when commands are later called. string wrappedStartupScript = @"if(!$orbPrivate_RunspaceInitialized){iex $orbPrivate_RunspaceStartupScript | Out-Null; $orbPrivate_RunspaceInitialized = $true};" + script; powerShell.AddScript(wrappedStartupScript); powerShell.AddCommand("Out-String"); activePowerShells[requestId] = powerShell; var result = new PSResult(); result.Output = string.Empty; result.Warnings = new List <string>(); result.Errors = new List <string>(); try { var output = await Task.Factory.FromAsync <PSDataCollection <PSObject>, PSInvocationSettings, PSDataCollection <PSObject> >( powerShell.BeginInvoke, powerShell.EndInvoke, new PSDataCollection <PSObject>(), new PSInvocationSettings(), null, TaskCreationOptions.None); foreach (var psObject in output) { result.Output += psObject.ToString().TrimEnd(); } foreach (var errorRecord in powerShell.Streams.Error) { result.Errors.Add(ErrorRecordToString(errorRecord)); } foreach (var warning in powerShell.Streams.Warning) { result.Warnings.Add(warning.ToString()); } } catch (Exception e) { result.Errors.Add(e.ToString()); Console.Write(e.ToString()); } finally { PowerShell dummy = null; activePowerShells.TryRemove(requestId, out dummy); powerShell.Dispose(); } return(result); }