internal void ReportEngineStartupError(ErrorRecord errorRecord) { try { Cmdlet cmdlet; string str; if (this.IsModuleCommandCurrentlyRunning(out cmdlet, out str)) { cmdlet.WriteError(errorRecord); } else { PSHost engineHostInterface = this.EngineHostInterface; if (engineHostInterface != null) { PSHostUserInterface uI = engineHostInterface.UI; if (uI != null) { uI.WriteErrorLine(errorRecord.ToString()); } } } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); } }
private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(ErrorRecord innerErrorRecord, string errorMessageTemplate) { string innerErrorMessage; if (innerErrorRecord.ErrorDetails != null && innerErrorRecord.ErrorDetails.Message != null) { innerErrorMessage = innerErrorRecord.ErrorDetails.Message; } else if (innerErrorRecord.Exception != null && innerErrorRecord.Exception.Message != null) { innerErrorMessage = innerErrorRecord.Exception.Message; } else { innerErrorMessage = innerErrorRecord.ToString(); } string errorMessage = string.Format( CultureInfo.InvariantCulture, errorMessageTemplate, innerErrorMessage); ErrorRecord outerErrorRecord = new ErrorRecord(innerErrorRecord, null /* null means: do not replace the exception */); ErrorDetails outerErrorDetails = new ErrorDetails(errorMessage); outerErrorRecord.ErrorDetails = outerErrorDetails; return(outerErrorRecord); }
/// <summary> /// Default implementation of WriteError - if the error record contains /// an exception then that exception will be thrown. If not, then an /// InvalidOperationException will be constructed and thrown. /// </summary> /// <param name="errorRecord">Error record instance to process</param> public void WriteError(ErrorRecord errorRecord) { if (errorRecord.Exception != null) throw errorRecord.Exception; else throw new InvalidOperationException(errorRecord.ToString()); }
private PSDataCollection <PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args) { string str; HostInfo hostInfo = this.remoteHost.HostInfo; IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start(); PSDataCollection <PSObject> datas = powershell.EndInvoke(asyncResult); ArrayList dollarErrorVariable = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable; if (dollarErrorVariable.Count <= 0) { return(datas); } ErrorRecord record = dollarErrorVariable[0] as ErrorRecord; if (record != null) { str = record.ToString(); } else { Exception exception = dollarErrorVariable[0] as Exception; if (exception != null) { str = (exception.Message != null) ? exception.Message : string.Empty; } else { str = string.Empty; } } throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), new object[] { str }); }
private static void AddErrorInfo(StringBuilder sb, ErrorRecord err) { sb.Append(err.ToString()); sb.AppendFormat("\r\n +{0}", err.InvocationInfo.PositionMessage); sb.AppendFormat("\r\n + CategoryInfo :{0}", err.CategoryInfo); sb.AppendFormat("\r\n + FullyQualifiedErrorId :{0}", err.FullyQualifiedErrorId.ToString()); sb.AppendLine(); }
public void WriteError(ErrorRecord errorRecord) { if (errorRecord.Exception != null) { throw errorRecord.Exception; } throw new InvalidOperationException(errorRecord.ToString()); }
internal static void CheckHostRemotingPrerequisites() { if (IsWinPEHost()) { ErrorRecord record = new ErrorRecord(new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.WinPERemotingNotSupported, new object[0])), null, ErrorCategory.InvalidOperation, null); throw new InvalidOperationException(record.ToString()); } }
public void ThrowTerminatingError(ErrorRecord errorRecord) { if (errorRecord.Exception != null) { throw errorRecord.Exception; } throw new InvalidOperationException(errorRecord.ToString()); }
public void ThrowTerminatingError(ErrorRecord errorRecord) { if (errorRecord.Exception != null) { throw errorRecord.Exception; } else { throw new System.InvalidOperationException(errorRecord.ToString()); } }
public void ThrowTerminatingError(ErrorRecord errorRecord) { if (CommandRuntime == null) { if (errorRecord.Exception != null) { throw errorRecord.Exception; } throw new InvalidOperationException(errorRecord.ToString()); } CommandRuntime.ThrowTerminatingError(errorRecord); }
internal static RuntimeException ConvertToException(object result, IScriptExtent extent) { result = PSObject.Base(result); RuntimeException exception = result as RuntimeException; if (exception != null) { InterpreterError.UpdateExceptionErrorRecordPosition(exception, extent); exception.WasThrownFromThrowStatement = true; return(exception); } ErrorRecord errorRecord = result as ErrorRecord; if (errorRecord != null) { exception = new RuntimeException(errorRecord.ToString(), errorRecord.Exception, errorRecord) { WasThrownFromThrowStatement = true }; InterpreterError.UpdateExceptionErrorRecordPosition(exception, extent); return(exception); } Exception exception3 = result as Exception; if (exception3 != null) { errorRecord = new ErrorRecord(exception3, exception3.Message, ErrorCategory.OperationStopped, null); exception = new RuntimeException(exception3.Message, exception3, errorRecord) { WasThrownFromThrowStatement = true }; InterpreterError.UpdateExceptionErrorRecordPosition(exception, extent); return(exception); } string message = LanguagePrimitives.IsNull(result) ? "ScriptHalted" : ParserOps.ConvertTo <string>(result, PositionUtilities.EmptyExtent); exception3 = new RuntimeException(message, null); errorRecord = new ErrorRecord(exception3, message, ErrorCategory.OperationStopped, null); exception = new RuntimeException(message, exception3, errorRecord) { WasThrownFromThrowStatement = true }; exception.SetTargetObject(result); InterpreterError.UpdateExceptionErrorRecordPosition(exception, extent); return(exception); }
public void TargetObjectIsString() { var ex = new ApplicationException("Exception error message"); var error = new ErrorRecord(ex, "errorId", ErrorCategory.AuthenticationError, "targetObject"); Assert.AreEqual("Exception error message", error.ToString()); Assert.AreEqual("errorId", error.FullyQualifiedErrorId); Assert.IsNull(error.ErrorDetails); Assert.AreEqual(ex, error.Exception); Assert.AreEqual("targetObject", error.TargetObject); Assert.AreEqual("", error.CategoryInfo.Activity); Assert.AreEqual(ErrorCategory.AuthenticationError, error.CategoryInfo.Category); Assert.AreEqual("ApplicationException", error.CategoryInfo.Reason); Assert.AreEqual("targetObject", error.CategoryInfo.TargetName); Assert.AreEqual("String", error.CategoryInfo.TargetType); Assert.AreEqual("AuthenticationError: (targetObject:String) [], ApplicationException", error.CategoryInfo.ToString()); Assert.AreEqual("AuthenticationError: (targetObject:String) [], ApplicationException", error.CategoryInfo.GetMessage()); }
public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { if (errorRecord == null) { throw new ArgumentNullException("errorRecord"); } if (base.commandRuntime == null) { if (errorRecord.Exception != null) { throw errorRecord.Exception; } throw new InvalidOperationException(errorRecord.ToString()); } base.commandRuntime.ThrowTerminatingError(errorRecord); } }
private static ErrorRecord GetErrorRecordForRemotePipelineInvocation(ErrorRecord innerErrorRecord, string errorMessageTemplate) { string str; if ((innerErrorRecord.ErrorDetails != null) && (innerErrorRecord.ErrorDetails.Message != null)) { str = innerErrorRecord.ErrorDetails.Message; } else if ((innerErrorRecord.Exception != null) && (innerErrorRecord.Exception.Message != null)) { str = innerErrorRecord.Exception.Message; } else { str = innerErrorRecord.ToString(); } string message = string.Format(CultureInfo.InvariantCulture, errorMessageTemplate, new object[] { str }); ErrorRecord record = new ErrorRecord(innerErrorRecord, null); ErrorDetails details = new ErrorDetails(message); record.ErrorDetails = details; return(record); }
private static string GetErrorMessage(ErrorRecord errorRecord) { var sb = new StringBuilder(errorRecord.ToString()); sb.Append(errorRecord.InvocationInfo.PositionMessage); return sb.ToString(); }
/// <summary> /// Facilitates to check if remoting is supported on the host machine. /// PowerShell remoting is supported on all Windows SQU's except WinPE. /// </summary> /// <exception cref="InvalidOperationException"> /// When PowerShell is hosted on a WinPE machine, the execution /// of this API would result in an InvalidOperationException being /// thrown, indicating that remoting is not supported on a WinPE machine. /// </exception> internal static void CheckHostRemotingPrerequisites() { // A registry key indicates if the SKU is WINPE. If this turns out to be true, // then an InValidOperation exception is thrown. bool isWinPEHost = Utils.IsWinPEHost(); if (isWinPEHost) { // WSMan is not supported on this platform //throw new InvalidOperationException( // "WinPE does not support Windows PowerShell remoting"); ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.WinPERemotingNotSupported)), null, ErrorCategory.InvalidOperation, null); throw new InvalidOperationException(errorRecord.ToString()); } }
public void WriteErrorRecord(System.Management.Automation.ErrorRecord errorRecord) { Console.WriteLine(ConsoleColor.Red, ConsoleColor.Black, errorRecord.ToString()); }
private static string GetMessageFromErrorRecord(ErrorRecord record) { if(record.Exception != null) { return record.Exception.Message; } if(record.ErrorDetails != null) { return String.Format(CultureInfo.InvariantCulture, "Erro - {0} & Recommended action - {1}", record.ErrorDetails.Message, record.ErrorDetails.RecommendedAction); } return record.ToString(); }
private static LogEntryInfo GetLogEntryInfoFromMessage(ErrorRecord errorRecord) { string message; string file; int lineNumber; int columnNumber; if (!TryGetLineInfoFromMessages(errorRecord.ToString(), out message, out file, out lineNumber, out columnNumber)) { return null; } message = message + Environment.NewLine + string.Format(CultureInfo.CurrentCulture, Resources.CustomFileLineNumberFormat, file, lineNumber) + Environment.NewLine + errorRecord.ScriptStackTrace; return new LogEntryInfo( message: message, file: file, lineNumber: lineNumber, columnNumber: columnNumber); }
internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = new ActionPreference?()) { this.ThrowIfStopping(); if ((errorRecord.ErrorDetails != null) && (errorRecord.ErrorDetails.TextLookupError != null)) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogCommandHealthEvent(this.context, textLookupError, Severity.Warning); } this.pipelineProcessor.ExecutionFailed = true; if (this.shouldLogPipelineExecutionDetail) { this.pipelineProcessor.LogExecutionError(this.thisCommand.MyInvocation, errorRecord); } ActionPreference errorAction = this.ErrorAction; if (actionPreference.HasValue) { errorAction = actionPreference.Value; } if (ActionPreference.Ignore != errorAction) { if (errorAction == ActionPreference.SilentlyContinue) { this.AppendErrorToVariables(errorRecord); } else { if (ContinueStatus.YesToAll == this.lastErrorContinueStatus) { errorAction = ActionPreference.Continue; } switch (errorAction) { case ActionPreference.Stop: { ActionPreferenceStopException e = new ActionPreferenceStopException(this.MyInvocation, errorRecord, this.CBResourcesBaseName, "ErrorPreferenceStop", new object[] { "ErrorActionPreference", errorRecord.ToString() }); throw this.ManageException(e); } case ActionPreference.Inquire: this.lastErrorContinueStatus = this.InquireHelper(RuntimeException.RetrieveMessage(errorRecord), null, true, false, true); break; } this.AppendErrorToVariables(errorRecord); PSObject obj2 = PSObject.AsPSObject(errorRecord); if (obj2.Members["writeErrorStream"] == null) { PSNoteProperty member = new PSNoteProperty("writeErrorStream", true); obj2.Properties.Add(member); } if (this.ErrorMergeTo != MergeDataStream.None) { this.OutputPipe.AddWithoutAppendingOutVarList(obj2); } else { this.ErrorOutputPipe.AddWithoutAppendingOutVarList(obj2); } } } }
public PowershellError(ErrorRecord error) { InnerError = error; Message = error.ToString(); }
} // DoWriteError // NOTICE-2004/06/08-JonN 959638 // Use this variant to skip the ThrowIfWriteNotPermitted check /// <exception cref="System.Management.Automation.PipelineStoppedException"> /// The pipeline has already been terminated, or was terminated /// during the execution of this method. /// The Cmdlet should generally just allow PipelineStoppedException /// to percolate up to the caller of ProcessRecord etc. /// </exception> /// <remarks> /// If the pipeline is terminated due to ActionPreference.Stop /// or ActionPreference.Inquire, this method will throw /// <see cref="System.Management.Automation.PipelineStoppedException"/>, /// but the command failure will ultimately be /// <see cref="System.Management.Automation.ActionPreferenceStopException"/>, /// </remarks> internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = null, bool isNativeError = false) { ThrowIfStopping(); if (null != errorRecord.ErrorDetails && null != errorRecord.ErrorDetails.TextLookupError) { Exception textLookupError = errorRecord.ErrorDetails.TextLookupError; errorRecord.ErrorDetails.TextLookupError = null; MshLog.LogCommandHealthEvent( Context, textLookupError, Severity.Warning); } this.PipelineProcessor.ExecutionFailed = true; if (LogPipelineExecutionDetail) { this.PipelineProcessor.LogExecutionError(_thisCommand.MyInvocation, errorRecord); } ActionPreference preference = ErrorAction; if (actionPreference.HasValue) { preference = actionPreference.Value; } // No trace of the error in the 'Ignore' case if (ActionPreference.Ignore == preference) { return; // do not write or record to output pipe } // 2004/05/26-JonN // The object is not written in the SilentlyContinue case if (ActionPreference.SilentlyContinue == preference) { AppendErrorToVariables(errorRecord); return; // do not write to output pipe } if (ContinueStatus.YesToAll == lastErrorContinueStatus) { preference = ActionPreference.Continue; } switch (preference) { case ActionPreference.Stop: ActionPreferenceStopException e = new ActionPreferenceStopException( MyInvocation, errorRecord, StringUtil.Format(CommandBaseStrings.ErrorPreferenceStop, "ErrorActionPreference", errorRecord.ToString())); throw ManageException(e); case ActionPreference.Inquire: // ignore return value // this will throw if the user chooses not to continue lastErrorContinueStatus = InquireHelper( RuntimeException.RetrieveMessage(errorRecord), null, true, // allowYesToAll false, // allowNoToAll true, // replaceNoWithHalt false // hasSecurityImpact ); break; } // switch (preference) // 2005/01/20 Do not write the object to $error if // ManageException has already done so AppendErrorToVariables(errorRecord); // Add this note property and set its value to true for F&O // to decide whether to call WriteErrorLine or WriteLine. // We want errors to print in red in both cases. PSObject errorWrap = PSObject.AsPSObject(errorRecord); // It's possible we've already added the member (this method is recursive sometimes // when tracing), so don't add the member again. // We don't add a note property on messages that comes from stderr stream. if (!isNativeError && errorWrap.Members["writeErrorStream"] == null) { PSNoteProperty note = new PSNoteProperty("writeErrorStream", true); errorWrap.Properties.Add(note); } // 2003/11/19-JonN Previously, PSObject instances in ErrorOutputPipe // wrapped the TargetObject and held the CoreException as a note. // Now, they wrap the CoreException and hold the TargetObject as a note. if (ErrorMergeTo != MergeDataStream.None) { Dbg.Assert(ErrorMergeTo == MergeDataStream.Output, "Only merging to success output is supported."); this.OutputPipe.AddWithoutAppendingOutVarList(errorWrap); } else { // If this is an error pipe for a hosting application and we are logging, // then create a temporary PowerShell to log the error. if (Context.InternalHost.UI.IsTranscribing) { Context.InternalHost.UI.TranscribeError(Context, errorRecord.InvocationInfo, errorWrap); } this.ErrorOutputPipe.AddWithoutAppendingOutVarList(errorWrap); } }
internal void LogExecutionError(InvocationInfo invocationInfo, ErrorRecord errorRecord) { if (errorRecord != null) { string item = StringUtil.Format(PipelineStrings.PipelineExecutionNonTerminatingError, this.GetCommand(invocationInfo), errorRecord.ToString()); this.logBuffer.Add(item); } }
private void WriteErrorRecord(RemoteComputer powershellComputer, ErrorRecord record) { powershellComputer.AddLogEntry(new LogEntry(powershellComputer.Name, record.ToString(), LogEntryType.Error)); }