#pragma warning disable 1591 protected override void ProcessRecord() {//process each item in the pipeline try { task = Task <int> .Factory.StartNew(() => { return(Start(FilePath, args, WorkingDirectory, LogPath)); }); task.Wait(); Console.WriteLine(task.Result); if (task.Result != 0) { var e = new System.Management.Automation.RuntimeException(String.Format("{0} ExitCode:{1}", FilePath, task.Result)); var errorRecord = new ErrorRecord(e, "StartExe-Fail", ErrorCategory.InvalidResult, null); WriteError(errorRecord); } } catch (AggregateException ae) { var errorRecord = new ErrorRecord(ae.InnerException, "StartExe-Fail", ErrorCategory.InvalidResult, null); WriteError(errorRecord); Console.WriteLine("Task has " + task.Status.ToString()); Console.WriteLine(ae.InnerException); } finally { task.Dispose(); } }
internal PSParseError(RuntimeException rte) { Dbg.Assert(rte != null, "exception argument should not be null"); Dbg.Assert(rte.ErrorToken != null, "token for exception should not be null"); Message = rte.Message; Token = new PSToken(rte.ErrorToken); }
#pragma warning disable 1591 protected override void ProcessRecord() {//process each item in the pipeline string target = string.Format("'{0}' {1} at {2}", FilePath, args, WorkingDirectory); if (ShouldProcess(target, "Start")) { try { task = Task <int> .Factory.StartNew(() => { return(Start(FilePath, args, WorkingDirectory, LogPathStdout, LogPathStderr)); }); do { Debug.WriteLine("ProcessRecord-Message Pump Loop"); Application.DoEvents(); }while (!_autoResetEvent.WaitOne(250)); Application.DoEvents(); task.Wait(); Trace.WriteLine(string.Format("Task.Result='{0}'", task.Result)); if (!exitCodeList.Contains(task.Result)) { string ExitCodeCsv = string.Empty; ExitCodeCsv = string.Join(",", exitCodeList.Select(p => p)); var e = new System.Management.Automation.RuntimeException(String.Format("{0} ExitCode '{1}' not in valid exit codes ({2})", FilePath, task.Result, ExitCodeCsv)); var errorRecord = new ErrorRecord(e, string.Format("Unexpected ExitCode of {0} for {1}", task.Result, FilePath), ErrorCategory.InvalidResult, null); WriteError(errorRecord); } } catch (AggregateException ae) { var errorRecord = new ErrorRecord(ae.InnerException, "Unexpected ExitCode for " + ae.InnerException.Message, ErrorCategory.InvalidResult, null); Console.WriteLine("Task has {0}", task.Status); Console.WriteLine(ae.InnerException); WriteError(errorRecord); } finally { task.Dispose(); } WriteObject(task.Result); } }
internal static RuntimeException NewInterpreterExceptionByMessage(Type exceptionType, IScriptExtent errorPosition, string message, string errorId, Exception innerException) { RuntimeException exception; if (exceptionType == typeof(ParseException)) { exception = new ParseException(message, errorId, innerException); } else if (exceptionType == typeof(IncompleteParseException)) { exception = new IncompleteParseException(message, errorId, innerException); } else { exception = new RuntimeException(message, innerException); exception.SetErrorId(errorId); exception.SetErrorCategory(ErrorCategory.InvalidOperation); } if (errorPosition != null) { exception.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition)); } return exception; }
internal static RuntimeException NewInterpreterExceptionByMessage(Type exceptionType, IScriptExtent errorPosition, string message, string errorId, Exception innerException) { RuntimeException exception; if (exceptionType == typeof(ParseException)) { exception = new ParseException(message, errorId, innerException); } else if (exceptionType == typeof(IncompleteParseException)) { exception = new IncompleteParseException(message, errorId, innerException); } else { exception = new RuntimeException(message, innerException); exception.SetErrorId(errorId); exception.SetErrorCategory(ErrorCategory.InvalidOperation); } if (errorPosition != null) { exception.ErrorRecord.SetInvocationInfo(new InvocationInfo(null, errorPosition)); } return(exception); }
internal Collection<PSSession> GetDisconnectedSessions(Collection<WSManConnectionInfo> connectionInfos, PSHost host, ObjectStream stream, RunspaceRepository runspaceRepository, int throttleLimit, SessionFilterState filterState, Guid[] matchIds, string[] matchNames, string configurationName) { Collection<PSSession> collection = new Collection<PSSession>(); foreach (WSManConnectionInfo info in connectionInfos) { Runspace[] runspaceArray = null; try { runspaceArray = Runspace.GetRunspaces(info, host, BuiltInTypesTable); } catch (RuntimeException exception) { if (!(exception.InnerException is InvalidOperationException)) { throw; } if ((stream.ObjectWriter != null) && stream.ObjectWriter.IsOpen) { int num; string message = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, info.ComputerName, ExtractMessage(exception.InnerException, out num)); string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError(num, "RemotePSSessionQueryFailed"); Exception exception2 = new RuntimeException(message, exception.InnerException); ErrorRecord errorRecord = new ErrorRecord(exception2, fQEIDFromTransportError, ErrorCategory.InvalidOperation, info); stream.ObjectWriter.Write(errorRecord); /* stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }); */ } } if (this.stopProcessing) { break; } if (runspaceArray != null) { string str3 = null; if (!string.IsNullOrEmpty(configurationName)) { str3 = (configurationName.IndexOf("http://schemas.microsoft.com/powershell/", StringComparison.OrdinalIgnoreCase) != -1) ? configurationName : ("http://schemas.microsoft.com/powershell/" + configurationName); } foreach (Runspace runspace in runspaceArray) { if (str3 != null) { WSManConnectionInfo connectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; if ((connectionInfo != null) && !str3.Equals(connectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; } } PSSession item = null; if (runspaceRepository != null) { item = runspaceRepository.GetItem(runspace.InstanceId); } if ((item != null) && UseExistingRunspace(item.Runspace, runspace)) { if (this.TestRunspaceState(item.Runspace, filterState)) { collection.Add(item); } } else if (this.TestRunspaceState(runspace, filterState)) { collection.Add(new PSSession(runspace as RemoteRunspace)); } } } } if ((matchIds != null) && (collection.Count > 0)) { Collection<PSSession> collection2 = new Collection<PSSession>(); foreach (Guid guid in matchIds) { bool flag = false; foreach (PSSession session2 in collection) { if (this.stopProcessing) { break; } if (session2.Runspace.InstanceId.Equals(guid)) { flag = true; collection2.Add(session2); break; } } if ((!flag && (stream.ObjectWriter != null)) && stream.ObjectWriter.IsOpen) { Exception exception3 = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.SessionIdMatchFailed, guid)); ErrorRecord errorRecord = new ErrorRecord(exception3, "PSSessionIdMatchFail", ErrorCategory.InvalidOperation, guid); stream.ObjectWriter.Write(errorRecord); /* stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }); */ } } return collection2; } if ((matchNames == null) || (collection.Count <= 0)) { return collection; } Collection<PSSession> collection3 = new Collection<PSSession>(); foreach (string str5 in matchNames) { WildcardPattern pattern = new WildcardPattern(str5, WildcardOptions.IgnoreCase); bool flag2 = false; foreach (PSSession session3 in collection) { if (this.stopProcessing) { break; } if (pattern.IsMatch(((RemoteRunspace) session3.Runspace).RunspacePool.RemoteRunspacePoolInternal.Name)) { flag2 = true; collection3.Add(session3); } } if ((!flag2 && (stream.ObjectWriter != null)) && stream.ObjectWriter.IsOpen) { Exception exception4 = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.SessionNameMatchFailed, str5)); ErrorRecord errorRecord = new ErrorRecord(exception4, "PSSessionNameMatchFail", ErrorCategory.InvalidOperation, str5); stream.ObjectWriter.Write(errorRecord); /* stream.ObjectWriter.Write(delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }); */ } } return collection3; }
/// <summary> /// Queries the remote computer for the specified session, creates a disconnected /// session object, connects the runspace/command and collects command data. /// Command output is either returned (OutTarget.Host) or collected /// in a job object that is returned (OutTarget.Job). /// </summary> /// <param name="name">Name of session to find.</param> /// <param name="instanceId">Instance Id of session to find.</param> private void QueryForAndConnectCommands(string name, Guid instanceId) { WSManConnectionInfo connectionInfo = GetConnectionObject(); // Retrieve all disconnected runspaces on the remote computer. Runspace[] runspaces; try { runspaces = Runspace.GetRunspaces(connectionInfo, this.Host, QueryRunspaces.BuiltInTypesTable); } catch (System.Management.Automation.RuntimeException e) { int errorCode; string msg = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, connectionInfo.ComputerName, QueryRunspaces.ExtractMessage(e.InnerException, out errorCode)); string FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(errorCode, "ReceivePSSessionQueryForSessionFailed"); Exception reason = new RuntimeException(msg, e.InnerException); ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, connectionInfo); WriteError(errorRecord); return; } // Convert configuration name into shell Uri for comparison. string shellUri = null; if (!string.IsNullOrEmpty(ConfigurationName)) { shellUri = (ConfigurationName.IndexOf( System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase) != -1) ? ConfigurationName : System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix + ConfigurationName; } // Connect selected runspace/command and direct command output to host // or job objects. foreach (Runspace runspace in runspaces) { if (_stopProcessing) { break; } // Filter returned runspaces by ConfigurationName if provided. if (shellUri != null) { // Compare with returned shell Uri in connection info. WSManConnectionInfo wsmanConnectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null && !shellUri.Equals(wsmanConnectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; } } // Find specified session. bool haveMatch = false; if (!string.IsNullOrEmpty(name) && string.Compare(name, ((RemoteRunspace)runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase) == 0) { // Selected by friendly name. haveMatch = true; } else if (instanceId.Equals(runspace.InstanceId)) { // Selected by instance Id (note that session/runspace/runspacepool instanceIds are identical.) haveMatch = true; } if (haveMatch && ShouldProcess(((RemoteRunspace)runspace).PSSessionName, VerbsCommunications.Receive)) { // Check the local repository for an existing viable session. PSSession locSession = this.RunspaceRepository.GetItem(runspace.InstanceId); // Connect the session here. If it fails (connectedSession == null) revert to the // reconstruct method. Exception ex; PSSession connectedSession = ConnectSession(locSession, out ex); if (connectedSession != null) { // Make sure that this connected session is included in the PSSession repository. // If it already exists then replace it because we want the latest/connected session in the repository. this.RunspaceRepository.AddOrReplace(connectedSession); // Since we have a local runspace we will do a *reconnect* operation and will // need the corresponding job object. PSRemotingJob job = FindJobForSession(connectedSession); if (this.OutTarget == OutTarget.Host) { ConnectSessionToHost(connectedSession, job); } else { // Connection to Job is default option. ConnectSessionToJob(connectedSession, job); } } else { // Otherwise create a new session from the queried runspace object. // This will be a *reconstruct* operation. // Create and connect session. PSSession newSession = new PSSession(runspace as RemoteRunspace); connectedSession = ConnectSession(newSession, out ex); if (connectedSession != null) { // Try to reuse the existing local repository PSSession object. if (locSession != null) { connectedSession = locSession.InsertRunspace(connectedSession.Runspace as RemoteRunspace) ? locSession : connectedSession; } // Make sure that this connected session is included in the PSSession repository. // If it already exists then replace it because we want the latest/connected session in the repository. this.RunspaceRepository.AddOrReplace(connectedSession); if (this.OutTarget == OutTarget.Job) { ConnectSessionToJob(connectedSession); } else { // Connection to Host is default option. ConnectSessionToHost(connectedSession); } } else { String message = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, newSession.Name); WriteError(new ErrorRecord(new ArgumentException(message, ex), "ReceivePSSessionCannotConnectSession", ErrorCategory.InvalidOperation, newSession)); } } break; } } }
private void WriteDisconnectFailed(Exception e = null) { if (_writeStream.ObjectWriter.IsOpen) { string msg; if (e != null && !string.IsNullOrWhiteSpace(e.Message)) { msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailedWithReason, _remoteSession.InstanceId, e.Message); } else { msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailed, _remoteSession.InstanceId); } Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionDisconnectFailed", ErrorCategory.InvalidOperation, _remoteSession); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; _writeStream.ObjectWriter.Write(errorWriter); } }
private void QueryForAndConnectCommands(string name, Guid instanceId) { Runspace[] runspaceArray; WSManConnectionInfo connectionObject = this.GetConnectionObject(); try { runspaceArray = Runspace.GetRunspaces(connectionObject, base.Host, QueryRunspaces.BuiltInTypesTable); } catch (RuntimeException exception) { int num; string message = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, connectionObject.ComputerName, QueryRunspaces.ExtractMessage(exception.InnerException, out num)); string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError(num, "ReceivePSSessionQueryForSessionFailed"); Exception exception2 = new RuntimeException(message, exception.InnerException); ErrorRecord errorRecord = new ErrorRecord(exception2, fQEIDFromTransportError, ErrorCategory.InvalidOperation, connectionObject); base.WriteError(errorRecord); return; } string str3 = null; if (!string.IsNullOrEmpty(this.ConfigurationName)) { str3 = (this.ConfigurationName.IndexOf("http://schemas.microsoft.com/powershell/", StringComparison.OrdinalIgnoreCase) != -1) ? this.ConfigurationName : ("http://schemas.microsoft.com/powershell/" + this.ConfigurationName); } foreach (Runspace runspace in runspaceArray) { if (this._stopProcessing) { return; } if (str3 != null) { WSManConnectionInfo connectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; if ((connectionInfo != null) && !str3.Equals(connectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; } } bool flag = false; if (!string.IsNullOrEmpty(name) && (string.Compare(name, ((RemoteRunspace) runspace).RunspacePool.RemoteRunspacePoolInternal.Name, StringComparison.OrdinalIgnoreCase) == 0)) { flag = true; } else if (instanceId.Equals(runspace.InstanceId)) { flag = true; } if (flag && base.ShouldProcess(((RemoteRunspace) runspace).Name, "Receive")) { Exception exception3; PSSession item = base.RunspaceRepository.GetItem(runspace.InstanceId); PSSession session2 = this.ConnectSession(item, out exception3); if (session2 != null) { base.RunspaceRepository.AddOrReplace(session2); PSRemotingJob job = this.FindJobForSession(session2); if (this.OutTarget == Microsoft.PowerShell.Commands.OutTarget.Host) { this.ConnectSessionToHost(session2, job); return; } this.ConnectSessionToJob(session2, job); return; } PSSession session = new PSSession(runspace as RemoteRunspace); session2 = this.ConnectSession(session, out exception3); if (session2 != null) { if (item != null) { session2 = item.InsertRunspace(session2.Runspace as RemoteRunspace) ? item : session2; } base.RunspaceRepository.AddOrReplace(session2); if (this.OutTarget == Microsoft.PowerShell.Commands.OutTarget.Job) { this.ConnectSessionToJob(session2, null); return; } this.ConnectSessionToHost(session2, null); return; } string str4 = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, session.Name); base.WriteError(new ErrorRecord(new ArgumentException(str4, exception3), "ReceivePSSessionCannotConnectSession", ErrorCategory.InvalidOperation, session)); return; } } }
internal WildcardPatternException(ErrorRecord errorRecord) : base(RuntimeException.RetrieveMessage(errorRecord)) => this._errorRecord = errorRecord != null ? errorRecord : throw new ArgumentNullException(nameof(errorRecord));
private void ExecuteStatement( ParseTreeNode statement, Array input, Pipe outputPipe, ref ArrayList resultList, ExecutionContext context) { ScriptTrace.TraceLine(context, statement); Exception e = (Exception)null; try { try { if (statement.IsVoidable) { statement.Execute(input, (Pipe)null, context); } else { statement.Execute(input, outputPipe, ref resultList, context); } ParseTreeNode parseTreeNode = statement; while (parseTreeNode is AssignmentStatementNode assignmentStatementNode) { parseTreeNode = assignmentStatementNode.RightHandSide; } if (parseTreeNode.IsExpression) { context.QuestionMarkVariableValue = true; } else if (parseTreeNode is PipelineNode pipelineNode) { context.QuestionMarkVariableValue = !pipelineNode.ExecutionFailed(context); } } catch (COMException ex) { throw InterpreterError.NewInterpreterExceptionWithInnerException((object)null, typeof(RuntimeException), statement.NodeToken, "COMException", (Exception)ex, (object)ex.Message); } catch (InvalidComObjectException ex) { throw InterpreterError.NewInterpreterExceptionWithInnerException((object)null, typeof(RuntimeException), statement.NodeToken, "InvalidComObjectException", (Exception)ex, (object)ex.Message); } } catch (ReturnException ex) { if (resultList == null || resultList.Count == 0) { e = (Exception)ex; } else { ParseTreeNode.AppendResult(context, ex.Argument, (Pipe)null, ref resultList); ex.SetArgument((object)resultList.ToArray()); resultList = (ArrayList)null; e = (Exception)ex; } } catch (RuntimeException ex) { e = this.HandleException(statement.NodeToken, ex, outputPipe, ref resultList, context); } if (e != null) { RuntimeException.LockStackTrace(e); throw e; } }
/// <summary> /// Stores the exception to be returned from /// PipelineProcessor.SynchronousExecute, and writes it to /// the error variable. /// </summary> /// /// <param name="e"> /// The exception which occurred during script execution /// </param> /// /// <exception cref="PipelineStoppedException"> /// ManageScriptException throws PipelineStoppedException if-and-only-if /// the exception is a RuntimeException, otherwise it returns. /// This allows the caller to rethrow unexpected exceptions. /// </exception> internal void ManageScriptException(RuntimeException e) { if (null != Command && null != commandRuntime.PipelineProcessor) { commandRuntime.PipelineProcessor.RecordFailure(e, Command); // An explicit throw is written to $error as an ErrorRecord, so we // skip adding what is more or less a duplicate. if (!(e is PipelineStoppedException) && !e.WasThrownFromThrowStatement) commandRuntime.AppendErrorToVariables(e); } // Upstream cmdlets see only that execution stopped throw new PipelineStoppedException(); }
internal CmdletInvocationException(ErrorRecord errorRecord) : base(RuntimeException.RetrieveMessage(errorRecord), RuntimeException.RetrieveException(errorRecord)) { this._errorRecord = errorRecord != null ? errorRecord : throw new ArgumentNullException(nameof(errorRecord)); Exception exception = errorRecord.Exception; }
private bool NeedToQueryForActionPreference(RuntimeException rte, ExecutionContext context) => !context.ExceptionHandlerInEnclosingStatementBlock && context.ShellFunctionErrorOutputPipe != null && (!context.CurrentPipelineStopping && !rte.SuppressPromptInInterpreter) && !(rte is PipelineStoppedException);
internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) : base(RuntimeException.RetrieveMessage(innerException), innerException) { if (innerException == null) { throw new ArgumentNullException("innerException"); } IContainsErrorRecord record = innerException as IContainsErrorRecord; if ((record != null) && (record.ErrorRecord != null)) { this._errorRecord = new System.Management.Automation.ErrorRecord(record.ErrorRecord, innerException); } else { this._errorRecord = new System.Management.Automation.ErrorRecord(innerException, innerException.GetType().FullName, ErrorCategory.NotSpecified, null); } this._errorRecord.SetInvocationInfo(invocationInfo); }
internal CmdletInvocationException(System.Management.Automation.ErrorRecord errorRecord) : base(RuntimeException.RetrieveMessage(errorRecord), RuntimeException.RetrieveException(errorRecord)) { if (errorRecord == null) { throw new ArgumentNullException("errorRecord"); } this._errorRecord = errorRecord; Exception exception = errorRecord.Exception; }
internal static void CheckActionPreference(FunctionContext funcContext, Exception exception) { ActionPreference preference; if (exception is TargetInvocationException) { exception = exception.InnerException; } CommandProcessorBase.CheckForSevereException(exception); RuntimeException exception2 = exception as RuntimeException; if (exception2 == null) { exception2 = ConvertToRuntimeException(exception, funcContext.CurrentPosition); } else { InterpreterError.UpdateExceptionErrorRecordPosition(exception2, funcContext.CurrentPosition); } RuntimeException.LockStackTrace(exception2); ExecutionContext context = funcContext._executionContext; Pipe outputPipe = funcContext._outputPipe; IScriptExtent scriptPosition = exception2.ErrorRecord.InvocationInfo.ScriptPosition; SetErrorVariables(scriptPosition, exception2, context, outputPipe); context.QuestionMarkVariableValue = false; bool flag = funcContext._traps.Any <Tuple <Type[], Action <FunctionContext>[], Type[]> >() && (funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item2 != null); if (!flag && !NeedToQueryForActionPreference(exception2, context)) { throw exception2; } if (flag) { preference = ProcessTraps(funcContext, exception2); } else { preference = QueryForAction(exception2, exception2.Message, context); } context.QuestionMarkVariableValue = false; switch (preference) { case ActionPreference.SilentlyContinue: case ActionPreference.Ignore: return; case ActionPreference.Stop: exception2.SuppressPromptInInterpreter = true; throw exception2; } if (!flag && exception2.WasThrownFromThrowStatement) { throw exception2; } bool flag2 = ReportErrorRecord(scriptPosition, exception2, context); context.QuestionMarkVariableValue = false; if (!flag2) { throw exception2; } }
/// <summary> /// Writes a "Load from job store" error to host. /// </summary> /// <param name="name">Scheduled job definition name</param> /// <param name="error">Exception thrown during loading</param> internal void WriteErrorLoadingDefinition(string name, Exception error) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadDefinitionFromStore, name); Exception reason = new RuntimeException(msg, error); ErrorRecord errorRecord = new ErrorRecord(reason, "CantLoadScheduledJobDefinitionFromStore", ErrorCategory.InvalidOperation, null); WriteError(errorRecord); }
internal ProviderInvocationException(System.Management.Automation.ProviderInfo provider, Exception innerException) : base(RuntimeException.RetrieveMessage(innerException), innerException) { this._message = base.Message; this._providerInfo = provider; IContainsErrorRecord record = innerException as IContainsErrorRecord; if ((record != null) && (record.ErrorRecord != null)) { this._errorRecord = new System.Management.Automation.ErrorRecord(record.ErrorRecord, innerException); } else { this._errorRecord = new System.Management.Automation.ErrorRecord(innerException, "ErrorRecordNotSpecified", ErrorCategory.InvalidOperation, null); } }
internal ActionPreferenceStopException(ErrorRecord error) : this(RuntimeException.RetrieveMessage(error)) => this._errorRecord = error != null ? error : throw new ArgumentNullException(nameof(error));
internal ProviderInvocationException(System.Management.Automation.ProviderInfo provider, System.Management.Automation.ErrorRecord errorRecord) : base(RuntimeException.RetrieveMessage(errorRecord), RuntimeException.RetrieveException(errorRecord)) { if (errorRecord == null) { throw new ArgumentNullException("errorRecord"); } this._message = base.Message; this._providerInfo = provider; this._errorRecord = errorRecord; }
internal PSParseError(RuntimeException rte) { this._message = rte.Message; this._psToken = new PSToken(rte.ErrorToken); }
private static string RetrieveMessage(string errorId, string resourceStr, System.Management.Automation.ProviderInfo provider, string path, Exception innerException) { if (innerException == null) { return(""); } if (string.IsNullOrEmpty(errorId)) { return(RuntimeException.RetrieveMessage(innerException)); } if (provider == null) { return(RuntimeException.RetrieveMessage(innerException)); } string str = resourceStr; if (string.IsNullOrEmpty(str)) { return(RuntimeException.RetrieveMessage(innerException)); } if (path == null) { return(string.Format(Thread.CurrentThread.CurrentCulture, str, new object[] { provider.Name, RuntimeException.RetrieveMessage(innerException) })); } return(string.Format(Thread.CurrentThread.CurrentCulture, str, new object[] { provider.Name, path, RuntimeException.RetrieveMessage(innerException) })); }
/// <summary> /// Wraps the exception which occurred during cmdlet invocation, /// stores that as the exception to be returned from /// PipelineProcessor.SynchronousExecute, and writes it to /// the error variable. /// </summary> /// <param name="e"> /// The exception to wrap in a CmdletInvocationException or /// CmdletProviderInvocationException. /// </param> /// <returns> /// Always returns PipelineStoppedException. The caller should /// throw this exception. /// </returns> /// <remarks> /// Almost all exceptions which occur during pipeline invocation /// are wrapped in CmdletInvocationException before they are stored /// in the pipeline. However, there are several exceptions: /// /// AccessViolationException, StackOverflowException: /// These are considered to be such severe errors that we /// FailFast the process immediately. /// /// ProviderInvocationException: In this case, we assume that the /// cmdlet is get-item or the like, a thin wrapper around the /// provider API. We discard the original ProviderInvocationException /// and re-wrap its InnerException (the real error) in /// CmdletProviderInvocationException. This makes it easier to reach /// the real error. /// /// CmdletInvocationException, ActionPreferenceStopException: /// This indicates that the cmdlet itself ran a command which failed. /// We could go ahead and wrap the original exception in multiple /// layers of CmdletInvocationException, but this makes it difficult /// for the caller to access the root problem, plus the serialization /// layer might not communicate properties beyond some fixed depth. /// Instead, we choose to not re-wrap the exception. /// /// PipelineStoppedException: This could mean one of two things. /// It usually means that this pipeline has already stopped, /// in which case the pipeline already stores the original error. /// It could also mean that the cmdlet ran a command which was /// stopped by CTRL-C etc, in which case we choose not to /// re-wrap the exception as with CmdletInvocationException. /// </remarks> internal PipelineStoppedException ManageInvocationException(Exception e) { try { if (Command != null) { do // false loop { ProviderInvocationException pie = e as ProviderInvocationException; if (pie != null) { // If a ProviderInvocationException occurred, // discard the ProviderInvocationException and // re-wrap in CmdletProviderInvocationException e = new CmdletProviderInvocationException( pie, Command.MyInvocation); break; } // 1021203-2005/05/09-JonN // HaltCommandException will cause the command // to stop, but not be reported as an error. // 906445-2005/05/16-JonN // FlowControlException should not be wrapped if (e is PipelineStoppedException || e is CmdletInvocationException || e is ActionPreferenceStopException || e is HaltCommandException || e is FlowControlException || e is ScriptCallDepthException) { // do nothing; do not rewrap these exceptions break; } RuntimeException rte = e as RuntimeException; if (rte != null && rte.WasThrownFromThrowStatement) { // do not rewrap a script based throw break; } // wrap all other exceptions e = new CmdletInvocationException( e, Command.MyInvocation); } while (false); // commandRuntime.ManageException will always throw PipelineStoppedException // Otherwise, just return this exception... // If this exception happened in a transacted cmdlet, // rollback the transaction if (commandRuntime.UseTransaction) { // The "transaction timed out" exception is // exceedingly obtuse. We clarify things here. bool isTimeoutException = false; Exception tempException = e; while (tempException != null) { if (tempException is System.TimeoutException) { isTimeoutException = true; break; } tempException = tempException.InnerException; } if (isTimeoutException) { ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException( TransactionStrings.TransactionTimedOut), "TRANSACTION_TIMEOUT", ErrorCategory.InvalidOperation, e); errorRecord.SetInvocationInfo(Command.MyInvocation); e = new CmdletInvocationException(errorRecord); } // Rollback the transaction in the case of errors. if ( _context.TransactionManager.HasTransaction && _context.TransactionManager.RollbackPreference != RollbackSeverity.Never ) { Context.TransactionManager.Rollback(true); } } return((PipelineStoppedException)this.commandRuntime.ManageException(e)); } // Upstream cmdlets see only that execution stopped // This should only happen if Command is null return(new PipelineStoppedException()); } catch (Exception) { // this method should not throw exceptions; warn about any violations on checked builds and re-throw Diagnostics.Assert(false, "This method should not throw exceptions!"); throw; } }
private int Start(string filePath, string args = "", string cwd = "", string logPath = "", string verb = "") { object _locker = new object(); Trace.WriteLine(string.Format("{0} {1}", filePath, args)); //* Create your Process Process process = new Process(); process.StartInfo.FileName = filePath; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = false; process.StartInfo.RedirectStandardError = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; bool isLogFileRedirect = (!String.IsNullOrEmpty(logPath)); //* Set output and error (asynchronous) handlers process.OutputDataReceived += (s, e) => { if (isLogFileRedirect) { lock (_locker) { File.AppendAllLines(logPath, new string[] { e.Data }); } } Console.WriteLine(e.Data); }; process.ErrorDataReceived += (s, e) => { if (isLogFileRedirect) { lock (_locker) { File.AppendAllLines(logPath, new string[] { "STDERR>", e.Data }); } } Console.WriteLine("STDERR>" + e.Data); }; process.Exited += (s, e) => { Console.WriteLine("Exit time: {0}\r\n" + "Exit code: {1}\r\n", process.ExitTime, process.ExitCode); }; //* Optional process configuration if (!String.IsNullOrEmpty(args)) { process.StartInfo.Arguments = args; } if (!String.IsNullOrEmpty(cwd)) { process.StartInfo.WorkingDirectory = cwd; } if (!String.IsNullOrEmpty(verb)) { process.StartInfo.Verb = verb; } //* Start process and handlers try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); _processId = process.Id; process.WaitForExit(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); var e = new System.Management.Automation.RuntimeException(String.Format("{0} ExitCode:{1}", FilePath, -1), ex); throw (e); } return(process.ExitCode); }
internal static void ThrowExceptionOnError(string errorId, Collection<string> independentErrors, Collection<PSSnapInTypeAndFormatErrors> PSSnapinFilesCollection, RunspaceConfigurationCategory category) { Collection<string> collection = new Collection<string>(); if (independentErrors != null) { foreach (string str in independentErrors) { collection.Add(str); } } foreach (PSSnapInTypeAndFormatErrors errors in PSSnapinFilesCollection) { foreach (string str2 in errors.Errors) { collection.Add(str2); } } if (collection.Count != 0) { StringBuilder builder = new StringBuilder(); builder.Append('\n'); foreach (string str3 in collection) { builder.Append(str3); builder.Append('\n'); } string message = ""; if (category == RunspaceConfigurationCategory.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, builder.ToString()); } else if (category == RunspaceConfigurationCategory.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, builder.ToString()); } RuntimeException exception = new RuntimeException(message); exception.SetErrorId(errorId); throw exception; } }
protected override void ProcessRecord() { string message; string str = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, this.Name); if (base.ShouldProcess(str, "Register")) { ScheduledJobDefinition scheduledJobDefinition = null; string parameterSetName = base.ParameterSetName; string str1 = parameterSetName; if (parameterSetName != null) { if (str1 == "ScriptBlock") { scheduledJobDefinition = this.CreateScriptBlockDefinition(); } else { if (str1 == "FilePath") { scheduledJobDefinition = this.CreateFilePathDefinition(); } } } if (scheduledJobDefinition != null) { if (base.MyInvocation.BoundParameters.ContainsKey("MaxResultCount")) { if (this.MaxResultCount >= 1) { scheduledJobDefinition.SetExecutionHistoryLength(this.MaxResultCount, false); } else { string str2 = StringUtil.Format(ScheduledJobErrorStrings.InvalidMaxResultCount, new object[0]); Exception runtimeException = new RuntimeException(str2); ErrorRecord errorRecord = new ErrorRecord(runtimeException, "InvalidMaxResultCountParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, null); base.WriteError(errorRecord); return; } } try { scheduledJobDefinition.Register(); base.WriteObject(scheduledJobDefinition); } catch (ScheduledJobException scheduledJobException1) { ScheduledJobException scheduledJobException = scheduledJobException1; if (scheduledJobException.InnerException == null || scheduledJobException.InnerException as UnauthorizedAccessException == null) { if (scheduledJobException.InnerException == null || scheduledJobException.InnerException as DirectoryNotFoundException == null) { if (scheduledJobException.InnerException == null || scheduledJobException.InnerException as InvalidDataContractException == null) { ErrorRecord errorRecord1 = new ErrorRecord(scheduledJobException, "CantRegisterScheduledJobDefinition", ErrorCategory.InvalidOperation, scheduledJobDefinition); base.WriteError(errorRecord1); } else { if (!string.IsNullOrEmpty(scheduledJobException.InnerException.Message)) { message = scheduledJobException.InnerException.Message; } else { message = string.Empty; } string str3 = message; object[] name = new object[2]; name[0] = scheduledJobDefinition.Name; name[1] = str3; string str4 = StringUtil.Format(ScheduledJobErrorStrings.CannotSerializeData, name); Exception exception = new RuntimeException(str4, scheduledJobException); ErrorRecord errorRecord2 = new ErrorRecord(exception, "CannotSerializeDataWhenRegisteringScheduledJobDefinition", ErrorCategory.InvalidData, scheduledJobDefinition); base.WriteError(errorRecord2); } } else { string str5 = StringUtil.Format(ScheduledJobErrorStrings.DirectoryNotFoundError, scheduledJobDefinition.Name); Exception runtimeException1 = new RuntimeException(str5, scheduledJobException); ErrorRecord errorRecord3 = new ErrorRecord(runtimeException1, "DirectoryNotFoundWhenRegisteringScheduledJobDefinition", ErrorCategory.ObjectNotFound, scheduledJobDefinition); base.WriteError(errorRecord3); } } else { string str6 = StringUtil.Format(ScheduledJobErrorStrings.UnauthorizedAccessError, scheduledJobDefinition.Name); Exception exception1 = new RuntimeException(str6, scheduledJobException); ErrorRecord errorRecord4 = new ErrorRecord(exception1, "UnauthorizedAccessToRegisterScheduledJobDefinition", ErrorCategory.PermissionDenied, scheduledJobDefinition); base.WriteError(errorRecord4); } } } return; } else { return; } }
/// <summary> /// Perform runspace disconnect processing on all input. /// </summary> protected override void ProcessRecord() { Dictionary<Guid, PSSession> psSessions; List<IThrottleOperation> disconnectOperations = new List<IThrottleOperation>(); try { // Get all remote runspaces to disconnect. if (ParameterSetName == DisconnectPSSessionCommand.SessionParameterSet) { if (Session == null || Session.Length == 0) { return; } psSessions = new Dictionary<Guid, PSSession>(); foreach (PSSession psSession in Session) { psSessions.Add(psSession.InstanceId, psSession); } } else { psSessions = GetMatchingRunspaces(false, true); } // Look for local sessions that have the EnableNetworkAccess property set and // return a string containing all of the session names. Emit a warning for // these sessions. string cnNames = GetLocalhostWithNetworkAccessEnabled(psSessions); if (!string.IsNullOrEmpty(cnNames)) { WriteWarning( StringUtil.Format(RemotingErrorIdStrings.EnableNetworkAccessWarning, cnNames)); } // Create a disconnect operation for each runspace to disconnect. foreach (PSSession psSession in psSessions.Values) { if (ShouldProcess(psSession.Name, VerbsCommunications.Disconnect)) { // PS session disconnection is not supported for VM/Container sessions. if (psSession.ComputerType != TargetMachineType.RemoteMachine) { // Write error record. string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeDisconnectedForVMContainerSession, psSession.Name, psSession.ComputerName, psSession.ComputerType); Exception reason = new PSNotSupportedException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "CannotDisconnectVMContainerSession", ErrorCategory.InvalidOperation, psSession); WriteError(errorRecord); continue; } // Can only disconnect an Opened runspace. if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) { // Update the connectionInfo object with passed in session options. if (_sessionOption != null) { psSession.Runspace.ConnectionInfo.SetSessionOptions(_sessionOption); } // Validate the ConnectionInfo IdleTimeout value against the MaxIdleTimeout // value returned by the server and the hard coded minimum allowed value. if (!ValidateIdleTimeout(psSession)) { continue; } DisconnectRunspaceOperation disconnectOperation = new DisconnectRunspaceOperation(psSession, _stream); disconnectOperations.Add(disconnectOperation); } else if (psSession.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected) { // Write error record. string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeDisconnected, psSession.Name); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "CannotDisconnectSessionWhenNotOpened", ErrorCategory.InvalidOperation, psSession); WriteError(errorRecord); } else { // Session is already disconnected. Write to output. WriteObject(psSession); } } } } catch (PSRemotingDataStructureException) { // Allow cmdlet to end and then re-throw exception. _operationsComplete.Set(); throw; } catch (PSRemotingTransportException) { // Allow cmdlet to end and then re-throw exception. _operationsComplete.Set(); throw; } catch (RemoteException) { // Allow cmdlet to end and then re-throw exception. _operationsComplete.Set(); throw; } catch (InvalidRunspaceStateException) { // Allow cmdlet to end and then re-throw exception. _operationsComplete.Set(); throw; } if (disconnectOperations.Count > 0) { // Make sure operations are not set as complete while processing input. _operationsComplete.Reset(); // Submit list of disconnect operations. _throttleManager.SubmitOperations(disconnectOperations); // Write any output now. Collection<object> streamObjects = _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { WriteStreamObject((Action<Cmdlet>)streamObject); } } }
private void RemoveFromJobDefinition(IEnumerable<ScheduledJobDefinition> definitions) { foreach (ScheduledJobDefinition definition in definitions) { List<Int32> notFoundIds = new List<int>(); try { notFoundIds = definition.RemoveTriggers(_triggerIds, true); } catch (ScheduledJobException e) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantRemoveTriggersFromDefinition, definition.Name); Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "CantRemoveTriggersFromScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); WriteError(errorRecord); } // Report not found errors. foreach (Int32 idNotFound in notFoundIds) { WriteTriggerNotFoundError(idNotFound, definition.Name, definition); } } }
/// <summary> /// Do the following actions: /// 1. If runspace is in opened state, /// a. stop any execution in process in the runspace /// b. close the runspace /// 2. Remove the runspace from the global cache /// </summary> protected override void ProcessRecord() { ICollection<PSSession> toRemove = null; switch (ParameterSetName) { case RemovePSSessionCommand.ComputerNameParameterSet: case RemovePSSessionCommand.NameParameterSet: case RemovePSSessionCommand.InstanceIdParameterSet: case RemovePSSessionCommand.IdParameterSet: case RemovePSSessionCommand.ContainerIdParameterSet: case RemovePSSessionCommand.VMIdParameterSet: case RemovePSSessionCommand.VMNameParameterSet: { Dictionary<Guid, PSSession> matches = GetMatchingRunspaces(false, true); toRemove = matches.Values; } break; case RemovePSSessionCommand.SessionParameterSet: { toRemove = Session; } break; default: Diagnostics.Assert(false, "Invalid Parameter Set"); toRemove = new Collection<PSSession>(); // initialize toRemove to turn off PREfast warning about it being null break; } foreach (PSSession remoteRunspaceInfo in toRemove) { RemoteRunspace remoteRunspace = (RemoteRunspace)remoteRunspaceInfo.Runspace; if (ShouldProcess(remoteRunspace.ConnectionInfo.ComputerName, "Remove")) { // If the remote runspace is in a disconnected state, first try to connect it so that // it can be removed from both the client and server. if (remoteRunspaceInfo.Runspace.RunspaceStateInfo.State == RunspaceState.Disconnected) { bool ConnectSucceeded; try { remoteRunspaceInfo.Runspace.Connect(); ConnectSucceeded = true; } catch (InvalidRunspaceStateException) { ConnectSucceeded = false; } catch (PSRemotingTransportException) { ConnectSucceeded = false; } if (!ConnectSucceeded) { // Write error notification letting user know that session cannot be removed // from server due to lack of connection. string msg = System.Management.Automation.Internal.StringUtil.Format( RemotingErrorIdStrings.RemoveRunspaceNotConnected, remoteRunspace.PSSessionName); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "RemoveSessionCannotConnectToServer", ErrorCategory.InvalidOperation, remoteRunspace); WriteError(errorRecord); // Continue removing the runspace from the client. } } try { // Dispose internally calls Close() and Close() // is a no-op if the state is not Opened, so just // dispose the runspace remoteRunspace.Dispose(); } catch (PSRemotingTransportException) { // just ignore, there is some transport error // on Close() } try { // Remove the runspace from the repository this.RunspaceRepository.Remove(remoteRunspaceInfo); } catch (ArgumentException) { // just ignore, the runspace may already have // been removed } } } }
/// <summary> /// Writes a "Trigger not found" error to host. /// </summary> /// <param name="notFoundId">Trigger Id not found</param> /// <param name="definitionName">ScheduledJobDefinition name</param> /// <param name="errorObject">Error object</param> internal void WriteTriggerNotFoundError( Int32 notFoundId, string definitionName, object errorObject) { string msg = StringUtil.Format(ScheduledJobErrorStrings.TriggerNotFound, notFoundId, definitionName); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "ScheduledJobTriggerNotFound", ErrorCategory.ObjectNotFound, errorObject); WriteError(errorRecord); }
private ScheduledJobDefinition CreateFilePathDefinition() { JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), this.FilePath, this._name); jobDefinition.ModuleName = "PSScheduledJob"; Dictionary<string, object> strs = this.CreateCommonParameters(); if (this.FilePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { Collection<PathInfo> resolvedPSPathFromPSPath = base.SessionState.Path.GetResolvedPSPathFromPSPath(this.FilePath); if (resolvedPSPathFromPSPath.Count == 1) { strs.Add("FilePath", resolvedPSPathFromPSPath[0].Path); JobInvocationInfo scheduledJobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, strs); ScheduledJobDefinition scheduledJobDefinition = new ScheduledJobDefinition(scheduledJobInvocationInfo, this.Trigger, this.ScheduledJobOption, this._credential); return scheduledJobDefinition; } else { string str = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePath, new object[0]); Exception runtimeException = new RuntimeException(str); ErrorRecord errorRecord = new ErrorRecord(runtimeException, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this); base.WriteError(errorRecord); return null; } } else { string str1 = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePathFile, new object[0]); Exception exception = new RuntimeException(str1); ErrorRecord errorRecord1 = new ErrorRecord(exception, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this); base.WriteError(errorRecord1); return null; } }
private static ActionPreference ProcessTraps(FunctionContext funcContext, RuntimeException rte) { int index = -1; Exception replaceParentContainsErrorRecordException = null; Exception innerException = rte.InnerException; Type[] types = funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item1; Action <FunctionContext>[] actionArray = funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item2; if (innerException != null) { index = FindMatchingHandlerByType(innerException.GetType(), types); replaceParentContainsErrorRecordException = innerException; } if ((index == -1) || types[index].Equals(typeof(CatchAll))) { int num2 = FindMatchingHandlerByType(rte.GetType(), types); if (num2 != index) { index = num2; replaceParentContainsErrorRecordException = rte; } } if (index != -1) { try { ErrorRecord errorRecord = rte.ErrorRecord; ExecutionContext context = funcContext._executionContext; if (context.CurrentCommandProcessor != null) { context.CurrentCommandProcessor.ForgetScriptException(); } try { MutableTuple tuple = MutableTuple.MakeTuple(funcContext._traps.Last <Tuple <Type[], Action <FunctionContext>[], Type[]> >().Item3[index], Compiler.DottedLocalsNameIndexMap); tuple.SetAutomaticVariable(AutomaticVariable.Underbar, new ErrorRecord(errorRecord, replaceParentContainsErrorRecordException), context); for (int i = 1; i < 9; i++) { tuple.SetValue(i, funcContext._localsTuple.GetValue(i)); } SessionStateScope scope = context.EngineSessionState.NewScope(false); context.EngineSessionState.CurrentScope = scope; scope.LocalsTuple = tuple; FunctionContext context2 = new FunctionContext { _scriptBlock = funcContext._scriptBlock, _sequencePoints = funcContext._sequencePoints, _executionContext = funcContext._executionContext, _boundBreakpoints = funcContext._boundBreakpoints, _outputPipe = funcContext._outputPipe, _breakPoints = funcContext._breakPoints, _localsTuple = tuple }; actionArray[index](context2); } catch (TargetInvocationException exception3) { throw exception3.InnerException; } finally { context.EngineSessionState.RemoveScope(context.EngineSessionState.CurrentScope); } return(QueryForAction(rte, replaceParentContainsErrorRecordException.Message, context)); } catch (ContinueException) { return(ActionPreference.SilentlyContinue); } catch (BreakException) { return(ActionPreference.Stop); } } return(ActionPreference.Stop); }
protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception failureException, out ErrorRecord failureErrorRecord) { RemotePipeline pipeline = helper.Pipeline as RemotePipeline; RemoteRunspace runspace = pipeline.GetRunspace() as RemoteRunspace; failureException = null; failureErrorRecord = null; if (helper.InternalException != null) { string errorId = "RemotePipelineExecutionFailed"; failureException = helper.InternalException; if ((failureException is InvalidRunspaceStateException) || (failureException is InvalidRunspacePoolStateException)) { errorId = "InvalidSessionState"; if (!string.IsNullOrEmpty(failureException.Source)) { errorId = string.Format(CultureInfo.InvariantCulture, "{0},{1}", new object[] { errorId, failureException.Source }); } } failureErrorRecord = new ErrorRecord(helper.InternalException, errorId, ErrorCategory.OperationStopped, helper); } else if (runspace.RunspaceStateInfo.State == RunspaceState.Broken) { failureException = runspace.RunspaceStateInfo.Reason; object computerName = runspace.ConnectionInfo.ComputerName; string str2 = null; PSRemotingTransportException exception = failureException as PSRemotingTransportException; string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception != null) ? exception.ErrorCode : 0, "PSSessionStateBroken"); if (exception != null) { str2 = "[" + runspace.ConnectionInfo.ComputerName + "] "; if (exception.ErrorCode == -2144108135) { string str4 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" }); str2 = str2 + str4; } else if (!string.IsNullOrEmpty(exception.Message)) { str2 = str2 + exception.Message; } else if (!string.IsNullOrEmpty(exception.TransportMessage)) { str2 = str2 + exception.TransportMessage; } } if (failureException == null) { failureException = new RuntimeException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { runspace.RunspaceStateInfo.State })); } failureErrorRecord = new ErrorRecord(failureException, computerName, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str2, null); } else if (pipeline.PipelineStateInfo.State == PipelineState.Failed) { object targetObject = runspace.ConnectionInfo.ComputerName; failureException = pipeline.PipelineStateInfo.Reason; if (failureException != null) { RemoteException exception2 = failureException as RemoteException; ErrorRecord errorRecord = null; if (exception2 != null) { errorRecord = exception2.ErrorRecord; } else { errorRecord = new ErrorRecord(pipeline.PipelineStateInfo.Reason, "JobFailure", ErrorCategory.OperationStopped, targetObject); } string str5 = ((RemoteRunspace)pipeline.GetRunspace()).ConnectionInfo.ComputerName; Guid instanceId = pipeline.GetRunspace().InstanceId; OriginInfo originInfo = new OriginInfo(str5, instanceId); failureErrorRecord = new RemotingErrorRecord(errorRecord, originInfo); } } }
protected override void ProcessRecord() { ICollection<PSSession> remoteRunspaceInfos = null; string parameterSetName = base.ParameterSetName; if (parameterSetName != null) { if ((!(parameterSetName == "ComputerName") && !(parameterSetName == "Name")) && (!(parameterSetName == "InstanceId") && !(parameterSetName == "Id"))) { if (parameterSetName == "Session") { remoteRunspaceInfos = this.remoteRunspaceInfos; goto Label_0076; } } else { remoteRunspaceInfos = base.GetMatchingRunspaces(false, true).Values; goto Label_0076; } } remoteRunspaceInfos = new Collection<PSSession>(); Label_0076: foreach (PSSession session in remoteRunspaceInfos) { RemoteRunspace targetObject = (RemoteRunspace) session.Runspace; if (base.ShouldProcess(targetObject.ConnectionInfo.ComputerName, "Remove")) { if (session.Runspace.RunspaceStateInfo.State == RunspaceState.Disconnected) { bool flag; try { session.Runspace.Connect(); flag = true; } catch (InvalidRunspaceStateException) { flag = false; } catch (PSRemotingTransportException) { flag = false; } if (!flag) { Exception exception = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.RemoveRunspaceNotConnected, targetObject.Name)); ErrorRecord errorRecord = new ErrorRecord(exception, "RemoveSessionCannotConnectToServer", ErrorCategory.InvalidOperation, targetObject); base.WriteError(errorRecord); } } try { targetObject.Dispose(); } catch (PSRemotingTransportException) { } try { base.RunspaceRepository.Remove(session); } catch (ArgumentException) { } } } }
private static string RetrieveMessage( string errorId, string resourceStr, ProviderInfo provider, string path, Exception innerException) { if (innerException == null) { Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs innerException"); return(string.Empty); } if (string.IsNullOrEmpty(errorId)) { Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs errorId"); return(RuntimeException.RetrieveMessage(innerException)); } if (provider == null) { Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage needs provider"); return(RuntimeException.RetrieveMessage(innerException)); } string format = resourceStr; if (string.IsNullOrEmpty(format)) { Diagnostics.Assert(false, "ProviderInvocationException.RetrieveMessage bad errorId " + errorId); return(RuntimeException.RetrieveMessage(innerException)); } string result = null; if (path == null) { result = string.Format( System.Globalization.CultureInfo.CurrentCulture, format, provider.Name, RuntimeException.RetrieveMessage(innerException)); } else { result = string.Format( System.Globalization.CultureInfo.CurrentCulture, format, provider.Name, path, RuntimeException.RetrieveMessage(innerException)); } return(result); }
protected override void ProcessRecord() { string str; ScheduledJobDefinition jobDefinitionById = null; string parameterSetName = base.ParameterSetName; string str1 = parameterSetName; if (parameterSetName != null) { if (str1 == "Definition") { jobDefinitionById = this._definition; } else { if (str1 == "DefinitionId") { jobDefinitionById = base.GetJobDefinitionById(this._definitionId, true); } else { if (str1 == "DefinitionName") { jobDefinitionById = base.GetJobDefinitionByName(this._definitionName, true); } } } } if (this.Enabled) { str = "Enable"; } else { str = "Disable"; } string str2 = str; if (jobDefinitionById != null && base.ShouldProcess(jobDefinitionById.Name, str2)) { try { jobDefinitionById.SetEnabled(this.Enabled, true); } catch (ScheduledJobException scheduledJobException1) { ScheduledJobException scheduledJobException = scheduledJobException1; string str3 = StringUtil.Format(ScheduledJobErrorStrings.CantSetEnableOnJobDefinition, jobDefinitionById.Name); Exception runtimeException = new RuntimeException(str3, scheduledJobException); ErrorRecord errorRecord = new ErrorRecord(runtimeException, "CantSetEnableOnScheduledJobDefinition", ErrorCategory.InvalidOperation, jobDefinitionById); base.WriteError(errorRecord); } if (this._passThru) { base.WriteObject(jobDefinitionById); } } }
/// <summary> /// Writes a "Definition not found for Name" error to host. /// </summary> /// <param name="name">Definition Name</param> internal void WriteDefinitionNotFoundByNameError( string name) { string msg = StringUtil.Format(ScheduledJobErrorStrings.DefinitionNotFoundByName, name); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "ScheduledJobDefinitionNotFoundByName", ErrorCategory.ObjectNotFound, null); WriteError(errorRecord); }
/// <summary> /// Queries all remote computers specified in collection of WSManConnectionInfo objects /// and returns disconnected PSSession objects ready for connection to server. /// Returned sessions can be matched to Guids or Names. /// </summary> /// <param name="connectionInfos">Collection of WSManConnectionInfo objects.</param> /// <param name="host">Host for PSSession objects.</param> /// <param name="stream">Out stream object.</param> /// <param name="runspaceRepository">Runspace repository.</param> /// <param name="throttleLimit">Throttle limit.</param> /// <param name="filterState">Runspace state filter value.</param> /// <param name="matchIds">Array of session Guids to match to.</param> /// <param name="matchNames">Array of session Names to match to.</param> /// <param name="configurationName">Configuration name to match to.</param> /// <returns>Collection of disconnected PSSession objects.</returns> internal Collection<PSSession> GetDisconnectedSessions(Collection<WSManConnectionInfo> connectionInfos, PSHost host, ObjectStream stream, RunspaceRepository runspaceRepository, int throttleLimit, SessionFilterState filterState, Guid[] matchIds, string[] matchNames, string configurationName) { Collection<PSSession> filteredPSSesions = new Collection<PSSession>(); // Create a query operation for each connection information object. foreach (WSManConnectionInfo connectionInfo in connectionInfos) { Runspace[] runspaces = null; try { runspaces = Runspace.GetRunspaces(connectionInfo, host, BuiltInTypesTable); } catch (System.Management.Automation.RuntimeException e) { if (e.InnerException is InvalidOperationException) { // The Get-WSManInstance cmdlet used to query remote computers for runspaces will throw // an Invalid Operation (inner) exception if the connectInfo object is invalid, including // invalid computer names. // We don't want to propagate the exception so just write error here. if (stream.ObjectWriter != null && stream.ObjectWriter.IsOpen) { int errorCode; string msg = StringUtil.Format(RemotingErrorIdStrings.QueryForRunspacesFailed, connectionInfo.ComputerName, ExtractMessage(e.InnerException, out errorCode)); string FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(errorCode, "RemotePSSessionQueryFailed"); Exception reason = new RuntimeException(msg, e.InnerException); ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, connectionInfo); stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord))); } } else { throw; } } if (_stopProcessing) { break; } // Add all runspaces meeting filter criteria to collection. if (runspaces != null) { // Convert configuration name into shell Uri for comparison. string shellUri = null; if (!string.IsNullOrEmpty(configurationName)) { shellUri = (configurationName.IndexOf( System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase) != -1) ? configurationName : System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix + configurationName; } foreach (Runspace runspace in runspaces) { // Filter returned runspaces by ConfigurationName if provided. if (shellUri != null) { // Compare with returned shell Uri in connection info. WSManConnectionInfo wsmanConnectionInfo = runspace.ConnectionInfo as WSManConnectionInfo; if (wsmanConnectionInfo != null && !shellUri.Equals(wsmanConnectionInfo.ShellUri, StringComparison.OrdinalIgnoreCase)) { continue; } } // Check the repository for an existing viable PSSession for // this runspace (based on instanceId). Use the existing // local runspace instead of the one returned from the server // query. PSSession existingPSSession = null; if (runspaceRepository != null) { existingPSSession = runspaceRepository.GetItem(runspace.InstanceId); } if (existingPSSession != null && UseExistingRunspace(existingPSSession.Runspace, runspace)) { if (TestRunspaceState(existingPSSession.Runspace, filterState)) { filteredPSSesions.Add(existingPSSession); } } else if (TestRunspaceState(runspace, filterState)) { filteredPSSesions.Add(new PSSession(runspace as RemoteRunspace)); } } } } // Return only PSSessions that match provided Ids or Names. if ((matchIds != null) && (filteredPSSesions.Count > 0)) { Collection<PSSession> matchIdsSessions = new Collection<PSSession>(); foreach (Guid id in matchIds) { bool matchFound = false; foreach (PSSession psSession in filteredPSSesions) { if (_stopProcessing) { break; } if (psSession.Runspace.InstanceId.Equals(id)) { matchFound = true; matchIdsSessions.Add(psSession); break; } } if (!matchFound && stream.ObjectWriter != null && stream.ObjectWriter.IsOpen) { string msg = StringUtil.Format(RemotingErrorIdStrings.SessionIdMatchFailed, id); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionIdMatchFail", ErrorCategory.InvalidOperation, id); stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord))); } } // Return all found sessions. return matchIdsSessions; } else if ((matchNames != null) && (filteredPSSesions.Count > 0)) { Collection<PSSession> matchNamesSessions = new Collection<PSSession>(); foreach (string name in matchNames) { WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase); bool matchFound = false; foreach (PSSession psSession in filteredPSSesions) { if (_stopProcessing) { break; } if (namePattern.IsMatch(((RemoteRunspace)psSession.Runspace).RunspacePool.RemoteRunspacePoolInternal.Name)) { matchFound = true; matchNamesSessions.Add(psSession); } } if (!matchFound && stream.ObjectWriter != null && stream.ObjectWriter.IsOpen) { string msg = StringUtil.Format(RemotingErrorIdStrings.SessionNameMatchFailed, name); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionNameMatchFail", ErrorCategory.InvalidOperation, name); stream.ObjectWriter.Write((Action<Cmdlet>)(cmdlet => cmdlet.WriteError(errorRecord))); } } return matchNamesSessions; } else { // Return all collected sessions. return filteredPSSesions; } }
internal void ManageScriptException(RuntimeException e) { if ((this.Command != null) && (this.commandRuntime.PipelineProcessor != null)) { this.commandRuntime.PipelineProcessor.RecordFailure(e, this.Command); if (!(e is PipelineStoppedException) && !e.WasThrownFromThrowStatement) { this.commandRuntime.AppendErrorToVariables(e); } } throw new PipelineStoppedException(); }
internal PSSession QueryForSession(PSSession session) { Collection<WSManConnectionInfo> wsManConnectionInfos = new Collection<WSManConnectionInfo>(); wsManConnectionInfos.Add(session.Runspace.ConnectionInfo as WSManConnectionInfo); Exception ex = null; Collection<PSSession> sessions = null; try { sessions = _queryRunspaces.GetDisconnectedSessions(wsManConnectionInfos, _host, _writeStream, null, 0, SessionFilterState.Disconnected, new Guid[] { session.InstanceId }, null, null); } catch (RuntimeException e) { ex = e; } if (ex != null) { WriteConnectFailed(ex, session); return null; } if (sessions.Count != 1) { ex = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.CannotFindSessionForConnect, session.Name, session.ComputerName)); WriteConnectFailed(ex, session); return null; } return sessions[0]; }
/// <summary> /// Handles state changes for Runspace /// </summary> /// <param name="sender">Sender of this event</param> /// <param name="stateEventArgs">Event information object which describes /// the event which triggered this method</param> private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs) { if (sender == null) { throw PSTraceSource.NewArgumentNullException("sender"); } if (stateEventArgs == null) { throw PSTraceSource.NewArgumentNullException("stateEventArgs"); } RunspaceStateEventArgs runspaceStateEventArgs = stateEventArgs.BaseEvent as RunspaceStateEventArgs; RunspaceStateInfo stateInfo = runspaceStateEventArgs.RunspaceStateInfo; RunspaceState state = stateInfo.State; OpenRunspaceOperation operation = sender as OpenRunspaceOperation; RemoteRunspace remoteRunspace = operation.OperatedRunspace; // since we got state changed event..we dont need to listen on // URI redirections anymore if (null != remoteRunspace) { remoteRunspace.URIRedirectionReported -= HandleURIDirectionReported; } PipelineWriter writer = _stream.ObjectWriter; Exception reason = runspaceStateEventArgs.RunspaceStateInfo.Reason; switch (state) { case RunspaceState.Opened: { // Indicates that runspace is successfully opened // Write it to PipelineWriter to be handled in // HandleRemoteRunspace PSSession remoteRunspaceInfo = new PSSession(remoteRunspace); this.RunspaceRepository.Add(remoteRunspaceInfo); Action<Cmdlet> outputWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteObject(remoteRunspaceInfo); }; if (writer.IsOpen) { writer.Write(outputWriter); } } break; case RunspaceState.Broken: { // Open resulted in a broken state. Extract reason // and write an error record // set the transport message in the error detail so that // the user can directly get to see the message without // having to mine through the error record details PSRemotingTransportException transException = reason as PSRemotingTransportException; String errorDetails = null; int transErrorCode = 0; if (transException != null) { OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation; transErrorCode = transException.ErrorCode; if (senderAsOp != null) { String host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName; if (transException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) { // Handling a special case for redirection..we should talk about // AllowRedirection parameter and WSManMaxRedirectionCount preference // variables string message = PSRemotingErrorInvariants.FormatResourceString( RemotingErrorIdStrings.URIRedirectionReported, transException.Message, "MaximumConnectionRedirectionCount", Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION, "AllowRedirection"); errorDetails = "[" + host + "] " + message; } else { errorDetails = "[" + host + "] "; if (!String.IsNullOrEmpty(transException.Message)) { errorDetails += transException.Message; } else if (!String.IsNullOrEmpty(transException.TransportMessage)) { errorDetails += transException.TransportMessage; } } } } // add host identification information in data structure handler message PSRemotingDataStructureException protoExeption = reason as PSRemotingDataStructureException; if (protoExeption != null) { OpenRunspaceOperation senderAsOp = sender as OpenRunspaceOperation; if (senderAsOp != null) { String host = senderAsOp.OperatedRunspace.ConnectionInfo.ComputerName; errorDetails = "[" + host + "] " + protoExeption.Message; } } if (reason == null) { reason = new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state)); } string fullyQualifiedErrorId = WSManTransportManagerUtils.GetFQEIDFromTransportError( transErrorCode, _defaultFQEID); if (WSManNativeApi.ERROR_WSMAN_NO_LOGON_SESSION_EXIST == transErrorCode) { errorDetails += System.Environment.NewLine + String.Format(System.Globalization.CultureInfo.CurrentCulture, RemotingErrorIdStrings.RemotingErrorNoLogonSessionExist); } ErrorRecord errorRecord = new ErrorRecord(reason, remoteRunspace, fullyQualifiedErrorId, ErrorCategory.OpenError, null, null, null, null, null, errorDetails, null); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { // // In case of PSDirectException, we should output the precise error message // in inner exception instead of the generic one in outer exception. // if ((errorRecord.Exception != null) && (errorRecord.Exception.InnerException != null)) { PSDirectException ex = errorRecord.Exception.InnerException as PSDirectException; if (ex != null) { errorRecord = new ErrorRecord(errorRecord.Exception.InnerException, errorRecord.FullyQualifiedErrorId, errorRecord.CategoryInfo.Category, errorRecord.TargetObject); } } cmdlet.WriteError(errorRecord); }; if (writer.IsOpen) { writer.Write(errorWriter); } _toDispose.Add(remoteRunspace); } break; case RunspaceState.Closed: { // The runspace was closed possibly because the user // hit ctrl-C when runspaces were being opened or Dispose has been // called when there are open runspaces Uri connectionUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(remoteRunspace.ConnectionInfo, "ConnectionUri", null); String message = GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, (connectionUri != null) ? connectionUri.AbsoluteUri : string.Empty); Action<Cmdlet> verboseWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteVerbose(message); }; if (writer.IsOpen) { writer.Write(verboseWriter); } // runspace may not have been opened in certain cases // like when the max memory is set to 25MB, in such // cases write an error record if (reason != null) { ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, remoteRunspace); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; if (writer.IsOpen) { writer.Write(errorWriter); } } } break; }// switch } // HandleRunspaceStateChanged
private void WriteConnectFailed( Exception e, PSSession session) { if (_writeStream.ObjectWriter.IsOpen) { string FQEID = "PSSessionConnectFailed"; Exception reason; if (e != null && !string.IsNullOrEmpty(e.Message)) { // Update fully qualified error Id if we have a transport error. PSRemotingTransportException transportException = e as PSRemotingTransportException; if (transportException != null) { FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(transportException.ErrorCode, FQEID); } reason = new RuntimeException( StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailedWithMessage, session.Name, e.Message), e); } else { reason = new RuntimeException( StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name, session.Runspace.RunspaceStateInfo.State.ToString()), null); } ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, null); Action<Cmdlet> errorWriter = delegate (Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; _writeStream.ObjectWriter.Write(errorWriter); } }
private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs) { ErrorRecord errorRecord; PSRemotingTransportException exception2; string str; if (sender == null) { throw PSTraceSource.NewArgumentNullException("sender"); } if (stateEventArgs == null) { throw PSTraceSource.NewArgumentNullException("stateEventArgs"); } RunspaceStateEventArgs baseEvent = stateEventArgs.BaseEvent as RunspaceStateEventArgs; RunspaceState state = baseEvent.RunspaceStateInfo.State; OpenRunspaceOperation operation = sender as OpenRunspaceOperation; RemoteRunspace operatedRunspace = operation.OperatedRunspace; if (operatedRunspace != null) { operatedRunspace.URIRedirectionReported -= new EventHandler<RemoteDataEventArgs<Uri>>(this.HandleURIDirectionReported); } PipelineWriter objectWriter = this.stream.ObjectWriter; Exception reason = baseEvent.RunspaceStateInfo.Reason; switch (state) { case RunspaceState.Opened: { PSSession remoteRunspaceInfo = new PSSession(operatedRunspace); base.RunspaceRepository.Add(remoteRunspaceInfo); Action<Cmdlet> action = cmdlet => cmdlet.WriteObject(remoteRunspaceInfo); if (objectWriter.IsOpen) { objectWriter.Write(action); } return; } case RunspaceState.Closed: { Uri uri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo<Uri>(operatedRunspace.ConnectionInfo, "ConnectionUri", null); string message = base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, new object[] { (uri != null) ? uri.AbsoluteUri : string.Empty }); Action<Cmdlet> action3 = cmdlet => cmdlet.WriteVerbose(message); if (objectWriter.IsOpen) { objectWriter.Write(action3); } if (reason != null) { ErrorRecord errorRecord2 = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, operatedRunspace); Action<Cmdlet> action4 = cmdlet => cmdlet.WriteError(errorRecord2); if (objectWriter.IsOpen) { objectWriter.Write(action4); } } return; } case RunspaceState.Closing: return; case RunspaceState.Broken: exception2 = reason as PSRemotingTransportException; str = null; if (exception2 != null) { OpenRunspaceOperation operation2 = sender as OpenRunspaceOperation; if (operation2 != null) { string computerName = operation2.OperatedRunspace.ConnectionInfo.ComputerName; if (exception2.ErrorCode != -2144108135) { str = "[" + computerName + "] "; if (!string.IsNullOrEmpty(exception2.Message)) { str = str + exception2.Message; } else if (!string.IsNullOrEmpty(exception2.TransportMessage)) { str = str + exception2.TransportMessage; } break; } string str3 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" }); str = "[" + computerName + "] " + str3; } } break; default: return; } PSRemotingDataStructureException exception3 = reason as PSRemotingDataStructureException; if (exception3 != null) { OpenRunspaceOperation operation3 = sender as OpenRunspaceOperation; if (operation3 != null) { string str4 = operation3.OperatedRunspace.ConnectionInfo.ComputerName; str = "[" + str4 + "] " + exception3.Message; } } if (reason == null) { reason = new RuntimeException(base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { state })); } string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception2 != null) ? exception2.ErrorCode : 0, this._defaultFQEID); errorRecord = new ErrorRecord(reason, operatedRunspace, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str, null); Action<Cmdlet> action2 = cmdlet => cmdlet.WriteError(errorRecord); if (objectWriter.IsOpen) { objectWriter.Write(action2); } this.toDispose.Add(operatedRunspace); }
/// <summary> /// Connect all disconnected sessions. /// </summary> private void ConnectSessions(Collection<PSSession> psSessions) { List<IThrottleOperation> connectOperations = new List<IThrottleOperation>(); // Create a disconnect operation for each runspace to disconnect. foreach (PSSession psSession in psSessions) { if (ShouldProcess(psSession.Name, VerbsCommunications.Connect)) { if (psSession.ComputerType != TargetMachineType.RemoteMachine) { // PS session disconnection is not supported for VM/Container sessions. string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnectedForVMContainerSession, psSession.Name, psSession.ComputerName, psSession.ComputerType); Exception reason = new PSNotSupportedException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "CannotConnectVMContainerSession", ErrorCategory.InvalidOperation, psSession); WriteError(errorRecord); } else if (psSession.Runspace.RunspaceStateInfo.State == RunspaceState.Disconnected && psSession.Runspace.RunspaceAvailability == RunspaceAvailability.None) { // Can only connect sessions that are in Disconnected state. // Update session connection information based on cmdlet parameters. UpdateConnectionInfo(psSession.Runspace.ConnectionInfo as WSManConnectionInfo); ConnectRunspaceOperation connectOperation = new ConnectRunspaceOperation( psSession, _stream, this.Host, null, _failedSessions); connectOperations.Add(connectOperation); } else if (psSession.Runspace.RunspaceStateInfo.State != RunspaceState.Opened) { // Write error record if runspace is not already in the Opened state. string msg = StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeConnected, psSession.Name); Exception reason = new RuntimeException(msg); ErrorRecord errorRecord = new ErrorRecord(reason, "PSSessionConnectFailed", ErrorCategory.InvalidOperation, psSession); WriteError(errorRecord); } else { // Session is already connected. Write to output. WriteObject(psSession); } } _allSessions.Add(psSession); } if (connectOperations.Count > 0) { // Make sure operations are not set as complete while processing input. _operationsComplete.Reset(); // Submit list of connect operations. _throttleManager.SubmitOperations(connectOperations); // Write any output now. Collection<object> streamObjects = _stream.ObjectReader.NonBlockingRead(); foreach (object streamObject in streamObjects) { WriteStreamObject((Action<Cmdlet>)streamObject); } } }
private void AddToJobDefinition(IEnumerable<ScheduledJobDefinition> jobDefinitions) { foreach (ScheduledJobDefinition definition in jobDefinitions) { try { definition.AddTriggers(_triggers, true); } catch (ScheduledJobException e) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantAddJobTriggersToDefinition, definition.Name); Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "CantAddJobTriggersToScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); WriteError(errorRecord); } } }
private void WriteDisconnectFailed(Exception e = null) { if (this.writeStream.ObjectWriter.IsOpen) { string str; if ((e != null) && !string.IsNullOrWhiteSpace(e.Message)) { str = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailedWithReason, this.remoteSession.InstanceId, e.Message); } else { str = StringUtil.Format(RemotingErrorIdStrings.RunspaceDisconnectFailed, this.remoteSession.InstanceId); } Exception exception = new RuntimeException(str, e); ErrorRecord errorRecord = new ErrorRecord(exception, "PSSessionDisconnectFailed", ErrorCategory.InvalidOperation, this.remoteSession); Action<Cmdlet> action = cmdlet => cmdlet.WriteError(errorRecord); this.writeStream.ObjectWriter.Write(action); } }
/// <summary> /// Process input. /// </summary> protected override void ProcessRecord() { List<ScheduledJobDefinition> definitions = null; switch (ParameterSetName) { case DefinitionParameterSet: definitions = new List<ScheduledJobDefinition>(_definitions); break; case DefinitionNameParameterSet: definitions = GetJobDefinitionsByName(_names); break; case DefinitionIdParameterSet: definitions = GetJobDefinitionsById(_definitionIds); break; } if (definitions != null) { foreach (ScheduledJobDefinition definition in definitions) { string targetString = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, definition.Name); if (ShouldProcess(targetString, VerbsLifecycle.Unregister)) { // Removes the ScheduledJobDefinition from the job store, // Task Scheduler, and disposes the object. try { definition.Remove(_force); } catch (ScheduledJobException e) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantUnregisterDefinition, definition.Name); Exception reason = new RuntimeException(msg, e); ErrorRecord errorRecord = new ErrorRecord(reason, "CantUnregisterScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); WriteError(errorRecord); } } } } // Check for unknown definition names. if ((_names != null && _names.Length > 0) && (_definitions == null || _definitions.Length < _names.Length)) { // Make sure there is no PowerShell task in Task Scheduler with removed names. // This covers the case where the scheduled job definition was manually removed from // the job store but remains as a PowerShell task in Task Scheduler. using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) { foreach (string name in _names) { taskScheduler.RemoveTaskByName(name, true, true); } } } }
protected override void ProcessRecord() { List<IThrottleOperation> operations = new List<IThrottleOperation>(); try { Dictionary<Guid, PSSession> matchingRunspaces; if (base.ParameterSetName == "Session") { if ((this.remotePSSessionInfo == null) || (this.remotePSSessionInfo.Length == 0)) { return; } matchingRunspaces = new Dictionary<Guid, PSSession>(); foreach (PSSession session in this.remotePSSessionInfo) { matchingRunspaces.Add(session.InstanceId, session); } } else { matchingRunspaces = base.GetMatchingRunspaces(false, true); } string localhostWithNetworkAccessEnabled = this.GetLocalhostWithNetworkAccessEnabled(matchingRunspaces); if (!string.IsNullOrEmpty(localhostWithNetworkAccessEnabled)) { base.WriteWarning(StringUtil.Format(RemotingErrorIdStrings.EnableNetworkAccessWarning, localhostWithNetworkAccessEnabled)); } foreach (PSSession session2 in matchingRunspaces.Values) { if (base.ShouldProcess(session2.Name, "Disconnect")) { if (session2.Runspace.RunspaceStateInfo.State == RunspaceState.Opened) { if (this.sessionOption != null) { session2.Runspace.ConnectionInfo.SetSessionOptions(this.sessionOption); } if (this.ValidateIdleTimeout(session2)) { DisconnectRunspaceOperation item = new DisconnectRunspaceOperation(session2, this.stream); operations.Add(item); } } else if (session2.Runspace.RunspaceStateInfo.State != RunspaceState.Disconnected) { Exception exception = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.RunspaceCannotBeDisconnected, session2.Name)); ErrorRecord errorRecord = new ErrorRecord(exception, "CannotDisconnectSessionWhenNotOpened", ErrorCategory.InvalidOperation, session2); base.WriteError(errorRecord); } else { base.WriteObject(session2); } } } } catch (PSRemotingDataStructureException) { this.operationsComplete.Set(); throw; } catch (PSRemotingTransportException) { this.operationsComplete.Set(); throw; } catch (RemoteException) { this.operationsComplete.Set(); throw; } catch (InvalidRunspaceStateException) { this.operationsComplete.Set(); throw; } if (operations.Count > 0) { this.operationsComplete.Reset(); this.throttleManager.SubmitOperations(operations); foreach (object obj2 in this.stream.ObjectReader.NonBlockingRead()) { base.WriteStreamObject((Action<Cmdlet>) obj2); } } }
internal static void ThrowExceptionOnError(string errorId, Collection<string> errors, RunspaceConfigurationCategory category) { if (errors.Count != 0) { StringBuilder builder = new StringBuilder(); builder.Append('\n'); foreach (string str in errors) { builder.Append(str); builder.Append('\n'); } string message = ""; if (category == RunspaceConfigurationCategory.Types) { message = StringUtil.Format(ExtendedTypeSystem.TypesXmlError, builder.ToString()); } else if (category == RunspaceConfigurationCategory.Formats) { message = StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatLoadingErrors, builder.ToString()); } RuntimeException exception = new RuntimeException(message); exception.SetErrorId(errorId); throw exception; } }
internal ActionPreferenceStopException(System.Management.Automation.ErrorRecord error) : this(RuntimeException.RetrieveMessage(error)) { if (error == null) { throw new ArgumentNullException("error"); } this._errorRecord = error; }