public static void DecodeTextureDataToWriter(byte[] data, int width, int height, TextureFormat format, PipelineWriter writer) { if (!format.IsSupported()) throw new FormatException("Unsupported format: " + format.ToString()); PipelineReader reader = null; switch (format) { case TextureFormat.DXT1: reader = new DXT1Reader(data, format, width, height); break; case TextureFormat.DXT2: case TextureFormat.DXT3: reader = new DXT3Reader(data, format, width, height); break; case TextureFormat.DXT4: case TextureFormat.DXT5: reader = new DXT5Reader(data, format, width, height); break; case TextureFormat.BC4: reader = new BC4Reader(data, format, width, height); break; case TextureFormat.BC5: reader = new BC5Reader(data, format, width, height); break; default: reader = new DefaultReader(data, format, width, height); break; } reader.Read(writer); }
public ICollection <PSObject> PipelineInvoke(Collection <Command> commands, out PipelineReader <object> Errors) { //Create Runspace if it has not already been created if (_runspace == null) { InitializeRunspace(); } ICollection <PSObject> results = null; Errors = null; if (IsConnect) { //Create Pipeline and add the commands Pipeline pipeline = _runspace.CreatePipeline(); foreach (Command item in commands) { pipeline.Commands.Add(item); } //Invoke the commands and return the results and errors results = pipeline.Invoke(); Errors = pipeline.Error; pipeline = null; return(results); } return(null); }
public static IObservable <T> ToObservable <T>(this PipelineReader <T> reader) { return(Observable.Create <T>(o => Observable.FromEventPattern( a => reader.DataReady += a, a => reader.DataReady -= a, Scheduler.CurrentThread) .StartWith(new EventPattern <object>(reader, EventArgs.Empty)) .Subscribe(_ => { //Debug.WriteLine($"PipeReaderThread: {Thread.CurrentThread.ManagedThreadId}"); do { foreach (var n in reader.NonBlockingRead()) { if (!AutomationNull.Value.Equals(n)) { o.OnNext(n); } else { ; //maybe multiple null inside stream are allowed } } }while (reader.Count > 0); if (reader.EndOfPipeline) { o.OnCompleted(); } } ))); }
public void Run(String command) { this.Log().Info("Running command: {0}", command); _pipeLine = _runSpace.CreatePipeline(command); _pipeLine.Input.Close(); _outPut = _pipeLine.Output; _outPut.DataReady += OutputDataReady; _pipeLine.InvokeAsync(); }
private void HandlePipelineErrorDataReady(object sender, EventArgs e) { PipelineReader <object> reader = sender as PipelineReader <object>; if (reader != null && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error); } }
public void Run(String command) { log.Info("Running command: " + command); _PipeLine = _RunSpace.CreatePipeline(command); _PipeLine.Input.Close(); _OutPut = _PipeLine.Output; _OutPut.DataReady += _Output_DataReady; _PipeLine.InvokeAsync(); }
private void ErrorObjectStreamHandler(object sender, EventArgs e) { PipelineReader <object> pipelineReader = (PipelineReader <object>)sender; Collection <object> objs = pipelineReader.NonBlockingRead(); foreach (object obj in objs) { this.parent.ErrorSerializer.Serialize(obj); } }
private void OutputObjectStreamHandler(object sender, EventArgs e) { PipelineReader <PSObject> pipelineReader = (PipelineReader <PSObject>)sender; Collection <PSObject> pSObjects = pipelineReader.NonBlockingRead(); foreach (PSObject pSObject in pSObjects) { this.parent.OutputSerializer.Serialize(pSObject); } }
private ICollection <PSObject> InvokePipelineInternal(Runspace runspace, Collection <Command> commands) { const string MethodName = "InvokePipelineInternal"; Debug.WriteLine(MethodName + ":entry", ClassName); Stopwatch watch = new Stopwatch(); watch.Start(); if (commands == null || commands.Count == 0) { throw new ArgumentException("Commands argument is null or empty"); } // make sure the output is set Collection <PSObject> results; // create the pipeline Pipeline pipe = runspace.CreatePipeline(); LOGGER_PERFORMANCE.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "InvokePipelineInternal: Pipeline created: {0} ms from start of this method", watch.ElapsedMilliseconds); // add the commands to the pipeline foreach (Command item in commands) { LOGGER_COMMANDS.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Item = {0}", item); foreach (CommandParameter cp in item.Parameters) { LOGGER_COMMANDS.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, " - parameter {0} = {1}", cp.Name, cp.Value); } pipe.Commands.Add(item); } LOGGER_COMMANDS.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Executing pipe: {0}", pipe); // run the pipeline if we have something to execute results = pipe.Invoke(); LOGGER_PERFORMANCE.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "InvokePipelineInternal: Pipeline.Invoke returned: {0} ms from start of this method", watch.ElapsedMilliseconds); PipelineReader <object> reader = pipe.Error; // check for errors CheckErrorsFromReader(reader); // an empty collection instead of null when we have executed if (results == null) { Debug.WriteLine("NO result returned"); results = new Collection <PSObject>(); } LOGGER_PERFORMANCE.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "InvokePipelineInternal: Method finishing: {0} ms from start of this method", watch.ElapsedMilliseconds); Debug.WriteLine(MethodName + ":exit", ClassName); return(results); }
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()); } } }
internal PipelineReader <object> GetObjectReaderForPipeline(string computerName, Guid runspaceId) { if (this._objectReaderForPipeline == null) { lock (this._syncObject) { if (this._objectReaderForPipeline == null) { this._objectReaderForPipeline = new PSDataCollectionPipelineReader <T, object>((PSDataCollectionStream <T>) this, computerName, runspaceId); } } } return(this._objectReaderForPipeline); }
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 HandleWarningsErrors(PipelineReader <object> pipelineerrors) { foreach (string warning in hostinterface.Warnings) { PSAlert.Add(warning, psmethods.PSAlert.AlertType.Warning); } if (pipelineerrors.Count > 0) { Collection <object> errors = pipelineerrors.ReadToEnd(); foreach (object error in errors) { PSAlert.Add(error.ToString(), psmethods.PSAlert.AlertType.Error); } } hostinterface.ClearWarnings(); }
/// <summary> /// invoke the powershell pipeline /// </summary> /// <param name="commands">a collection of commands to execute</param> /// <returns>collection of objects with the result /// if no command is passed in return null /// if no output from the invoke return an empty collection</returns> public ICollection <PSObject> InvokePipeline(Collection <Command> commands) { const string MethodName = "InvokePipeline"; Debug.WriteLine(MethodName + ":entry", ClassName); IList errors = null; if (commands == null || commands.Count == 0) { throw new ArgumentException("Commands argument is null or empty"); } // make sure the output is set errors = null; Collection <PSObject> results; // create the pipeline Pipeline pipe = this.runSpace.CreatePipeline(); // add the commands to the pipeline foreach (Command item in commands) { pipe.Commands.Add(item); } // run the pipeline if we have something to execute results = pipe.Invoke(); PipelineReader <object> reader = pipe.Error; errors = (IList)reader.ReadToEnd(); // check for errors CheckErrors(errors); // an empty collection instead of null when we have executed if (results == null) { Debug.WriteLine("NO result returned"); results = new Collection <PSObject>(); } Debug.WriteLine(MethodName + ":exit", ClassName); return(results); }
internal PipelineReader <object> GetObjectReaderForPipeline( string computerName, Guid runspaceId) { using (ObjectStreamBase._trace.TraceProperty()) { if (this._objectReaderForPipeline == null) { lock (this._syncObject) { if (this._objectReaderForPipeline == null) { this._objectReaderForPipeline = (PipelineReader <object>) new PSDataCollectionPipelineReader <T, object>(this, computerName, runspaceId); } } } return(this._objectReaderForPipeline); } }
// called on the pipeline thread private void ErrorObjectStreamHandler(object sender, EventArgs e) { // e is just an empty instance of EventArgs, so we ignore it. sender is the PipelineReader that raised it's // DataReady event that calls this handler, which is the PipelineReader for the Error object stream. PipelineReader <object> reader = (PipelineReader <object>)sender; // we use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be // inconsistent for this method to be called when there are no objects, since it will be called synchronously on // the pipeline thread, blocking in this call until an object is streamed would deadlock the pipeline. So we // prefer to take no chance of blocking. Collection <object> objects = reader.NonBlockingRead(); foreach (object obj in objects) { _parent.ErrorSerializer.Serialize(obj); } }
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; } }
public ICollection <PSObject> PipelineInvoke(IMsolCmdlet command, out PipelineReader <object> Errors) { //Create Runspace if it has not already been created if (_runspace == null) { InitializeRunspace(); } //Create Pipeline and add the command Pipeline pipeline = _runspace.CreatePipeline(); pipeline.Commands.Add(MsolCmdletExtensions.ToCommand(command)); //Invoke the command and return the results and errors ICollection <PSObject> results = pipeline.Invoke(); Errors = pipeline.Error; pipeline = null; return(results); }
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; } }
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); }
/// <summary> /// Checks whether errors reader contains some error, if so the errors are concatenated and exception is thrown, /// throws <see cref="ConnectorException"/> if the <paramref name="errors"/> parameter is not empty /// /// Introduced because of "Problem while PowerShell execution System.NotSupportedException: Specified method /// is not supported. at System.Management.Automation.Internal.PSDataCollectionPipelineReader`2.ReadToEnd()" /// (occurring on Exchange 2010/Windows Server 2008 R2) /// </summary> /// <param name="reader">pipeline reader</param> public static void CheckErrorsFromReader(PipelineReader <object> reader) { CheckErrorsFromReader(reader, DefaultThrowIcfExceptionImplementation); }
/// <summary> /// Checks whether errors reader contains some error, if so the errors are concatenated and exception is thrown, /// throws <see cref="ConnectorException"/> if the <paramref name="errors"/> parameter is not empty /// /// Introduced because of "Problem while PowerShell execution System.NotSupportedException: Specified method /// is not supported. at System.Management.Automation.Internal.PSDataCollectionPipelineReader`2.ReadToEnd()" /// (occurring on Exchange 2010/Windows Server 2008 R2) /// </summary> /// <param name="reader">pipeline reader</param> public static void CheckErrorsFromReader(PipelineReader<object> reader) { CheckErrorsFromReader(reader, DefaultThrowIcfExceptionImplementation); }
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); }
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> /// Determines the version of the Exchange server. /// </summary> /// <remarks>As the remote management functionality is not utilized, the Exchange powershell snap-in must be registered /// on the local computer. Different snap-in is used to manage Exchange 2007 and 2010, hence the server version is determined by the /// registered snap-in. /// </remarks> /// <returns>The version of the Exchange server to manage.</returns> /// <exception cref="ConnectorException">Thrown when the version cannot be determined.</exception> private ExchangeVersion GetExchangeServerVersion() { const string MethodName = "GetServerVersion"; Debug.WriteLine(MethodName + ":entry", ClassName); const string ExchangeSnapinNamePrefix = "Microsoft.Exchange.Management.PowerShell."; ExchangeVersion?version = null; using (var runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); using (var pipeline = runspace.CreatePipeline()) { var getSnapinsCommand = new Command("Get-PSSnapin"); getSnapinsCommand.Parameters.Add("Registered"); pipeline.Commands.Add(getSnapinsCommand); var snapinList = pipeline.Invoke(); PipelineReader <object> reader = pipeline.Error; CheckErrors((IList)reader.ReadToEnd()); runspace.Close(); if ((snapinList == null) || (snapinList.Count == 0)) { Debug.WriteLine("No snap-in returned"); throw new ConnectorException(_messageCatalog.Format("ex_NoPowerShellSnapins", "There are no registered PowerShell snap-ins.")); } foreach (var snapin in snapinList) { if ((snapin.Properties["Name"] != null) && (snapin.Properties["Name"].Value != null) && (snapin.Properties["Name"].Value.ToString().StartsWith(ExchangeSnapinNamePrefix, StringComparison.InvariantCultureIgnoreCase))) { var snapinName = snapin.Properties["Name"].Value.ToString(); switch (snapinName.Substring(ExchangeSnapinNamePrefix.Length)) { case "Admin": //Microsoft.Exchange.Management.PowerShell.Admin snap-in is used to manage Exchange 2007 version = ExchangeVersion.E2007; break; case "E2010": //Microsoft.Exchange.Management.PowerShell.E2010 snap-in is used to manage Exchange 2010 version = ExchangeVersion.E2010; break; } } } } } if (!version.HasValue) { throw new ConnectorException(_messageCatalog.Format("ex_NoSupportedExchangeSnapin", "There is no supported Exchange PowerShell snap-in registered.")); } Debug.WriteLine(MethodName + ":exit", ClassName); return(version.Value); }
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); }
private void HandleWarningsErrors(PipelineReader<object> pipelineerrors) { foreach (string warning in hostinterface.Warnings) { PSAlert.Add(warning, psmethods.PSAlert.AlertType.Warning); } if (pipelineerrors.Count > 0) { Collection<object> errors = pipelineerrors.ReadToEnd(); foreach (object error in errors) { PSAlert.Add(error.ToString(), psmethods.PSAlert.AlertType.Error); } } hostinterface.ClearWarnings(); }
/// <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 void OutputDataReady(object sender, EventArgs e) { try { PipelineReader <PSObject> reader = sender as PipelineReader <PSObject>; while (reader.Count > 0) { var r = _pipeline.Output.Read(); if (r == null) { // no-op } else if (r.BaseObject is System.Data.DataRow) { DataRow row = (DataRow)r.BaseObject; if (_resultDataTable == null) { _resultDataTable = row.Table.Clone(); _dataTableType = DataTableType.DataRow; } if (_dataTableType == DataTableType.DataRow) { _resultDataTable.ImportRow(row); } } else if (r.BaseObject is System.Management.Automation.PSCustomObject) { if (_resultDataTable == null) { SetDataTableFromPSCustomObject(r); _dataTableType = DataTableType.PSCustomObject; } if (_dataTableType == DataTableType.PSCustomObject) { ImportRowFromPSCustomObject(r); } } // Always output the object to string else { _resultStringBuilder.AppendLine(r.ToString()); } } } catch (Exception ex) { _taskCompleted = true; _endTime = DateTime.Now; _taskStatus = Status.FAILED; string logMessage = string.Format(@"SCRIPT FAILED. Time:[{0:MM/dd/yy HH:mm:ss}] Duration:[{1}] Error:{2}", DateTime.Now, this.Duration.ToString(@"hh\:mm\:ss"), ex.ToString()); _resultStringBuilder.Append(logMessage); return; } if (_pipeline.PipelineStateInfo.State == PipelineState.Running) { _taskCompleted = false; return; } else { if (_taskStatus == Status.RUNNING) { _taskStatus = Status.COMPLETED; } _taskCompleted = true; _endTime = DateTime.Now; string logMessage = string.Format("SCRIPT {0}. Time:[{1:MM/dd/yy HH:mm:ss}] Duration:[{2}]", TaskStatus.ToString(), DateTime.Now, this.Duration.ToString(@"hh\:mm\:ss")); _resultStringBuilder.Append(logMessage); _runspace.Close(); _runspace.Dispose(); return; } }
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; } }