private void Output_DataReadyExecutePsCmdlet(object sender, EventArgs e) { PipelineReader <PSObject> reader = sender as PipelineReader <PSObject>; if (reader != null) { while (reader.Count > 0) { Console.WriteLine(reader.Read().ToString()); } } }
private void Error_DataReadyExecutePsCmdlet(object sender, EventArgs e) { PipelineReader <Object> reader = sender as PipelineReader <Object>; if (reader != null) { while (reader.Count > 0) { _errorsExecutingCmdlet = true; Log(LogType.Error, reader.Read().ToString()); } } }
private void Error_DataReadyExecutePsCmdlet(object sender, EventArgs e) { PipelineReader<Object> reader = sender as PipelineReader<Object>; if (reader != null) { while (reader.Count > 0) { ErrorOccurred = true; object result = reader.Read(); _errorData.Add(result); Console.WriteLine(result.ToString()); } } }
public static void CheckErrorsFromReader(PipelineReader <object> reader, ThrowIcfExceptionDelegate throwIcfExceptionDelegate) { IList <ErrorRecord> errors = new List <ErrorRecord>(); while (true) { object error = reader.Read(); if (error == AutomationNull.Value) { break; } AddError(errors, error); } CheckErrors(errors, throwIcfExceptionDelegate); }
private void Output_DataReadyExecutePsCmdlet(object sender, EventArgs e) { PipelineReader<PSObject> reader = sender as PipelineReader<PSObject>; if (reader != null) { while (reader.Count > 0) { PSObject output = reader.Read(); if (output.BaseObject is System.String) { Console.WriteLine(output.ToString()); } _outputData.Add(output); } } }
private void ErrorDataReady(object sender, EventArgs e) { PipelineReader <object> reader = sender as PipelineReader <object>; if (reader != null) { while (reader.Count > 0) { _resultStringBuilder.AppendLine(reader.Read().ToString()); } } if (_pipeline.HadErrors) { if (_pipeline.PipelineStateInfo.Reason != null) { { _resultStringBuilder.AppendLine(_pipeline.PipelineStateInfo.Reason.ToString()); } } _taskStatus = Status.FAILED; } }
private void CheckErrorsInPipeline(Pipeline pipeline) { PipelineReader <object> pErrors = pipeline.Error; if (pErrors != null) { int errorCount = pErrors.Count; if (errorCount > 0) { Collection <object> errors = pErrors.Read(errorCount); if (errors == null) { throw new InvalidOperationException( "Invoke Read method from System.Management.Automation.Runspaces.PipelineReader<T> fail."); } foreach (object error in errors) { object errorRecordInstance = (error as PSObject).ImmediateBaseObject; if (errorRecordInstance != null) { object invocationInfoInstance = (errorRecordInstance as ErrorRecord).InvocationInfo; if (invocationInfoInstance != null) { string positionMessage = (invocationInfoInstance as InvocationInfo).PositionMessage; TestSite.Log.Add(LogEntryKind.CheckFailed, "PowerShell script write error '{0}' {1}", error, positionMessage); } } } } } }
static void HandleDataReady(object sender, EventArgs e) { PipelineReader <PSObject> output = sender as PipelineReader <PSObject>; if (output != null) { while (output.Count > 0) { Console.WriteLine("Output: {0}", output.Read()); } return; } PipelineReader <object> error = sender as PipelineReader <object>; if (error != null) { while (error.Count > 0) { Console.WriteLine("Error: {0}", error.Read()); } return; } }
public PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript, Action <Pipeline> additionalActionsBeforeScript) { // since we control output in the host, always set these true Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true"); var result = new PowerShellExecutionResults(); string commandToRun = wrap_script_with_module(chocoPowerShellScript, config); var host = new PoshHost(config); this.Log().Debug(() => "Calling built-in PowerShell host with ['{0}']".format_with(commandToRun.escape_curly_braces())); var initialSessionState = InitialSessionState.CreateDefault(); // override system execution policy without accidentally setting it initialSessionState.AuthorizationManager = new AuthorizationManager("choco"); using (var runspace = RunspaceFactory.CreateRunspace(host, initialSessionState)) { runspace.Open(); // this will affect actual execution policy //RunspaceInvoke invoker = new RunspaceInvoke(runspace); //invoker.Invoke("Set-ExecutionPolicy ByPass"); using (var pipeline = runspace.CreatePipeline()) { // The powershell host itself handles the following items: // * Write-Debug // * Write-Host // * Write-Verbose // * Write-Warning // // the two methods below will pick up Write-Output and Write-Error // Write-Output pipeline.Output.DataReady += (sender, args) => { PipelineReader <PSObject> reader = sender as PipelineReader <PSObject>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteLine(reader.Read().to_string().escape_curly_braces()); } } }; // Write-Error pipeline.Error.DataReady += (sender, args) => { PipelineReader <object> reader = sender as PipelineReader <object>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteErrorLine(reader.Read().to_string().escape_curly_braces()); } } }; var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify); var currentUserCurrentHostProfile = _fileSystem.combine_paths(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1"); var recreateProfileScript = @" if ((Test-Path(""{0}"")) -and ($profile -eq $null -or $profile -eq '')) {{ $global:profile = ""{1}"" }} ".format_with(documentsFolder, currentUserCurrentHostProfile); pipeline.Commands.Add(new Command(recreateProfileScript, isScript: true, useLocalScope: false)); // The PowerShell Output Redirection bug affects System.Management.Automation // it appears with v3 more than others. It is already known to affect v2 // this implements the redirection fix from the post below, fixed up with some comments // http://www.leeholmes.com/blog/2008/07/30/workaround-the-os-handles-position-is-not-what-filestream-expected/ const string outputRedirectionFixScript = @" try { $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $objectRef = $host.GetType().GetField(""externalHostRef"", $bindingFlags).GetValue($host) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetProperty"" $consoleHost = $objectRef.GetType().GetProperty(""Value"", $bindingFlags).GetValue($objectRef, @()) [void] $consoleHost.GetType().GetProperty(""IsStandardOutputRedirected"", $bindingFlags).GetValue($consoleHost, @()) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $field = $consoleHost.GetType().GetField(""standardOutputWriter"", $bindingFlags) $field.SetValue($consoleHost, [Console]::Out) [void] $consoleHost.GetType().GetProperty(""IsStandardErrorRedirected"", $bindingFlags).GetValue($consoleHost, @()) $field2 = $consoleHost.GetType().GetField(""standardErrorWriter"", $bindingFlags) $field2.SetValue($consoleHost, [Console]::Error) } catch { Write-Output ""Unable to apply redirection fix"" } "; pipeline.Commands.Add(new Command(outputRedirectionFixScript, isScript: true, useLocalScope: false)); if (additionalActionsBeforeScript != null) { additionalActionsBeforeScript.Invoke(pipeline); } pipeline.Commands.Add(new Command(commandToRun, isScript: true, useLocalScope: false)); try { pipeline.Invoke(); } catch (RuntimeException ex) { var errorStackTrace = ex.StackTrace; var record = ex.ErrorRecord; if (record != null) { // not available in v1 //errorStackTrace = record.ScriptStackTrace; var scriptStackTrace = record.GetType().GetProperty("ScriptStackTrace"); if (scriptStackTrace != null) { var scriptError = scriptStackTrace.GetValue(record, null).to_string(); if (!string.IsNullOrWhiteSpace(scriptError)) { errorStackTrace = scriptError; } } } this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, errorStackTrace.escape_curly_braces()))); } catch (Exception ex) { // Unfortunately this doesn't print line number and character. It might be nice to get back to those items unless it involves tons of work. this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, ex.StackTrace.escape_curly_braces()))); } if (pipeline.PipelineStateInfo != null) { switch (pipeline.PipelineStateInfo.State) { // disconnected is not available unless the assembly version is at least v3 //case PipelineState.Disconnected: case PipelineState.Running: case PipelineState.NotStarted: case PipelineState.Failed: case PipelineState.Stopping: case PipelineState.Stopped: if (host.ExitCode == 0) { host.SetShouldExit(1); } host.HostException = pipeline.PipelineStateInfo.Reason; break; case PipelineState.Completed: if (host.ExitCode == -1) { host.SetShouldExit(0); } break; } } } } this.Log().Debug("Built-in PowerShell host called with ['{0}'] exited with '{1}'.".format_with(commandToRun.escape_curly_braces(), host.ExitCode)); result.ExitCode = host.ExitCode; result.StandardErrorWritten = host.StandardErrorWritten; return(result); }
public static string RunScriptWithExitCode(string testScript) { string output = ""; string errorLogged = ""; try { //in order to ensure there is an exit code wrap it inside a PowerShell {} block testScript = "PowerShell {\r\n" + testScript + "\r\n}";//\r\n\"Exit code : $LASTEXITCODE\""; Collection <PSObject> results = null; Collection <PSObject> exitCodeResults = null; // create Powershell runspace using (Runspace runspace = RunspaceFactory.CreateRunspace()) { // open it runspace.Open(); runspace.StateChanged += Runspace_StateChanged; // create a pipeline and feed it the script text using (Pipeline pipeline = runspace.CreatePipeline()) { pipeline.Commands.AddScript(testScript); //pipeline.Commands.AddScript("$LASTEXITCODE"); // 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"); //pipeline.Commands.Add("$LASTEXITCODE"); //pipeline.Commands.AddScript("$LASTEXITCODE"); // execute the script lock (lockObject) { results = pipeline.Invoke(); } if (pipeline.HadErrors) { PipelineReader <object> errs = pipeline.Error; if (errs.Count > 0) { for (int i = 0; i < errs.Count; i++) { errorLogged += errs.Read().ToString() + "\r\n"; } System.Diagnostics.Trace.WriteLine($"Error: {errs.Read()}"); } } } using (Pipeline pipeline = runspace.CreatePipeline()) { pipeline.Commands.AddScript("$LASTEXITCODE"); pipeline.Commands.Add("Out-String"); // execute the script lock (lockObject) { exitCodeResults = pipeline.Invoke(); } } // close the runspace runspace.Close(); } // convert the script result into a single string StringBuilder stringBuilder = new StringBuilder(); if (results != null) { foreach (PSObject obj in results) { if (obj != null) { stringBuilder.AppendLine(obj.ToString()); } else { stringBuilder.AppendLine("[null]"); } } } else { stringBuilder.AppendLine("[null]"); } if (errorLogged.Length > 0) { stringBuilder.AppendLine($"Exception(s):{errorLogged}"); } if (exitCodeResults != null) { foreach (PSObject obj in exitCodeResults) { if (obj != null && obj.ToString() != "") { stringBuilder.AppendLine($"Exit code : {obj}"); System.Diagnostics.Trace.WriteLine($"Exit code : {obj}"); } } } else { stringBuilder.AppendLine($"Exit code : 0"); } output = stringBuilder.ToString(); } catch (Exception ex) { #if DEBUG output = $"Exception: {ex.ToString()}"; //output = $"Exception: {ex.GetMessageStack()}"; #else output = $"Exception: {ex.GetMessageStack()}"; #endif } return(output.Trim('\r', '\n')); }
/// <summary> /// Output data ready event handler. This event is called when /// there is data available from the output pipe. It reads the /// data available and displays it on the console. /// </summary> /// <param name="sender">The output pipe this event is associated with.</param> /// <param name="e">Unused</param> static void Output_DataReady(object sender, EventArgs e) { PipelineReader <PSObject> myp = (PipelineReader <PSObject>)sender; Console.WriteLine(myp.Read().ToString()); }
private PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript) { var result = new PowerShellExecutionResults(); string commandToRun = wrap_script_with_module(chocoPowerShellScript, config); var host = new PoshHost(config); this.Log().Debug(() => "Calling built-in PowerShell host with ['{0}']".format_with(commandToRun.escape_curly_braces())); var initialSessionState = InitialSessionState.CreateDefault(); // override system execution policy without accidentally setting it initialSessionState.AuthorizationManager = new AuthorizationManager("choco"); using (var runspace = RunspaceFactory.CreateRunspace(host, initialSessionState)) { runspace.Open(); // this will affect actual execution policy //RunspaceInvoke invoker = new RunspaceInvoke(runspace); //invoker.Invoke("Set-ExecutionPolicy ByPass"); using (var pipeline = runspace.CreatePipeline()) { // The powershell host itself handles the following items: // * Write-Debug // * Write-Host // * Write-Verbose // * Write-Warning // // the two methods below will pick up Write-Output and Write-Error // Write-Output pipeline.Output.DataReady += (sender, args) => { PipelineReader <PSObject> reader = sender as PipelineReader <PSObject>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteLine(reader.Read().to_string()); } } }; // Write-Error pipeline.Error.DataReady += (sender, args) => { PipelineReader <object> reader = sender as PipelineReader <object>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteErrorLine(reader.Read().to_string()); } } }; pipeline.Commands.Add(new Command(commandToRun, isScript: true, useLocalScope: false)); try { pipeline.Invoke(); } catch (Exception ex) { // Unfortunately this doesn't print line number and character. It might be nice to get back to those items unless it involves tons of work. this.Log().Error("ERROR: {0}".format_with(ex.Message)); //, !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine,ex.StackTrace))); } if (pipeline.PipelineStateInfo != null) { switch (pipeline.PipelineStateInfo.State) { // disconnected is not available unless the assembly version is at least v3 //case PipelineState.Disconnected: case PipelineState.Running: case PipelineState.NotStarted: case PipelineState.Failed: case PipelineState.Stopping: case PipelineState.Stopped: host.SetShouldExit(1); host.HostException = pipeline.PipelineStateInfo.Reason; break; case PipelineState.Completed: host.SetShouldExit(0); break; } } } } this.Log().Debug("Built-in PowerShell host called with ['{0}'] exited with '{1}'.".format_with(commandToRun.escape_curly_braces(), host.ExitCode)); result.ExitCode = host.ExitCode; result.StandardErrorWritten = host.StandardErrorWritten; return(result); }
public static void CheckErrorsFromReader(PipelineReader<object> reader, ThrowIcfExceptionDelegate throwIcfExceptionDelegate) { IList<ErrorRecord> errors = new List<ErrorRecord>(); while (true) { object error = reader.Read(); if (error == AutomationNull.Value) { break; } AddError(errors, error); } CheckErrors(errors, throwIcfExceptionDelegate); }
protected static ICollection <PSObject> ExecuteCmdlet(string cmdlet, PSParameters parms) { parms.Add(new PSParameter("DomainController", PreferDC)); if (cmdlet == null) { throw new ArgumentNullException("cmdlet"); } if (cmdlet.Length == 0) { throw new ArgumentException("cmdlet length is zero", "cmdlet"); } Command item = new Command(cmdlet); foreach (PSParameter parameter in parms) { item.Parameters.Add(parameter.Name, parameter.Value); } ICollection <PSObject> is2 = null; Pipeline pipeline = null; PipelineReader <object> error = null; PSObject obj2 = null; ErrorRecord baseObject = null; try { lock (sync) { SubmitSecurity subSecurity = new SubmitSecurity(); if (subSecurity.impersonateValidUser(DomainAdmin, Domain, DomainAdminPass)) { pipeline = _runspace.CreatePipeline(); using (Pipeline pipeline2 = pipeline) { pipeline.Commands.Add(item); is2 = pipeline.Invoke(); error = pipeline.Error; if (error.Count == 1) { obj2 = (PSObject)error.Read(); baseObject = (ErrorRecord)obj2.BaseObject; throw baseObject.Exception; } if (error.Count <= 1) { return(is2); } int count = error.Count; int num2 = 0; ErrorRecord record2 = null; while (error.Count > 0) { obj2 = (PSObject)error.Read(); baseObject = (ErrorRecord)obj2.BaseObject; if (record2 == null) { record2 = baseObject; } num2++; } throw record2.Exception; } } return(is2); } } finally { pipeline = null; } }
/// <summary> /// Output data arrived. /// </summary> /// <param name="sender">Contains the result as List of strings.</param> /// <param name="EventArgs"/>The instance containing the event data.</param> internal void Output_DataReady(object sender, EventArgs e) { PipelineReader <PSObject> output = sender as PipelineReader <PSObject>; List <string> lStringOutput = new List <string>(); List <object> lOutput = new List <object>(); if (output != null) { Collection <PSObject> pso = output.NonBlockingRead(); if (pso.Count > 0) { //Forward the Raw data... if (this.RawOutput != null) { this.RawOutput.Invoke(pso, e); } foreach (PSObject PO in pso) { if (PO != null) { lStringOutput.Add(PO.ToString()); foreach (string sType in PO.TypeNames) { ConvertThroughString cts = new ConvertThroughString(); Type objectType = Type.GetType(sType.Replace("Deserialized.", "")); if (cts.CanConvertFrom(PO, objectType)) { try { lOutput.Add(cts.ConvertFrom(PO, objectType, null, true)); break; } catch { try { System.Collections.Hashtable HT = new System.Collections.Hashtable(); foreach (PSPropertyInfo PI in PO.Properties) { try { HT.Add(PI.Name, PI.Value.ToString()); } catch { } } lOutput.Add(HT); break; } catch { } //break; } } else { } } } } } if (output.EndOfPipeline & output.IsOpen) { output.Close(); } } else { PipelineReader <object> error = sender as PipelineReader <object>; if (error != null) { while (error.Count > 0) { lStringOutput.Add(error.Read().ToString()); lOutput.Add(error.Read()); } if (error.EndOfPipeline) { error.Close(); } if (this.ErrorOccured != null) { this.ErrorOccured.Invoke(sender, e); } _autoResetEvent.Set(); } } //Forward output as ListOfStrings if (this.StringOutput != null) { this.StringOutput.Invoke(lStringOutput, e); } if (this.TypedOutput != null) { this.TypedOutput.Invoke(lOutput, e); } _autoResetEvent.Set(); }