Example #1
0
        void scriptErrorEventHandler(object sender, DataAddedEventArgs e)
        {
            ErrorRecord newRecord = ((PSDataCollection <ErrorRecord>)sender)[e.Index];

            ScriptsAppendOutputText("ERROR: " + newRecord.ToString() + "\n");

            Console.WriteLine(newRecord.ToString());
        }
Example #2
0
        private static void RunCommand(string command)
        {
            Task.Run(() => {
                HostUserInterface.output.Clear();
                using (var ps = PowerShell.Create())
                {
                    ps.Runspace = runspace;
                    ps.AddScript(command);
                    ps.AddCommand("Out-Default");

                    ps.Streams.Error.DataAdded += (sender, args) => {
                        ErrorRecord err = ((PSDataCollection <ErrorRecord>)sender)[args.Index];
                        Application.MainLoop.Invoke(() => {
                            MessageBox.ErrorQuery(20, 10, "Error", err.ToString(), "Ok");
                        });
                    };

                    try
                    {
                        ps.Invoke();
                    }
                    catch (Exception ex)
                    {
                        Application.MainLoop.Invoke(() => {
                            MessageBox.ErrorQuery(20, 10, "Error", ex.Message, "Ok");
                        });
                    }
                }
            });
        }
Example #3
0
        private void OnError(object sender, DataAddedEventArgs e)
        {
            var         data   = (PSDataCollection <ErrorRecord>)sender;
            ErrorRecord record = data[e.Index];

            WriteError(record.ToString());
        }
Example #4
0
        public void ParserShould_GenerateMethod_WithTwoPrintExpression()
        {
            // arrange
            var input = @"
main(x: integer, y : integer) : integer 
    print(x)
    print(y)
    x+1";

            // act
            var parser = new Parser()
            {
                EnableStackTrace = true
            };
            var errorRecord = new ErrorRecord(input);
            var program     = (Program)parser.Parse(new Tokenizer(input), errorRecord);

            // assert
            if (program == null)
            {
                Console.WriteLine(errorRecord.ToString());
            }
            Assert.That(program.Definitions[0].Body.Prints, Is.AstEqual(new ReadOnlyCollection <Print>(new List <Print>
            {
                new Print(0, new Identifier(0, "x")),
                new Print(0, new Identifier(0, "y")),
            })));
        }
Example #5
0
            public void Error_DataAdded(object sender, DataAddedEventArgs e)
            {
                var         errorCollection = (PSDataCollection <ErrorRecord>)sender;
                ErrorRecord errorRecord     = errorCollection[e.Index];

                Console.WriteLine("Error: {0}", 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());
     }
 }
Example #7
0
 public void ThrowTerminatingError(ErrorRecord errorRecord)
 {
     if (errorRecord.Exception != null)
     {
         throw errorRecord.Exception;
     }
     throw new InvalidOperationException(errorRecord.ToString());
 }
Example #8
0
 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();
 }
        private void WriteExceptionToHost(Exception e)
        {
            const string ExceptionFormat =
                "{0}\r\n{1}\r\n    + CategoryInfo          : {2}\r\n    + FullyQualifiedErrorId : {3}";

            IContainsErrorRecord containsErrorRecord = e as IContainsErrorRecord;

            if (containsErrorRecord == null ||
                containsErrorRecord.ErrorRecord == null)
            {
                this.WriteError(e.Message, null, 0, 0);
                return;
            }

            ErrorRecord errorRecord = containsErrorRecord.ErrorRecord;

            if (errorRecord.InvocationInfo == null)
            {
                this.WriteError(errorRecord.ToString(), String.Empty, 0, 0);
                return;
            }

            string errorRecordString = errorRecord.ToString();

            if ((errorRecord.InvocationInfo.PositionMessage != null) &&
                errorRecordString.IndexOf(errorRecord.InvocationInfo.PositionMessage, StringComparison.Ordinal) != -1)
            {
                this.WriteError(errorRecordString);
                return;
            }

            string message =
                string.Format(
                    CultureInfo.InvariantCulture,
                    ExceptionFormat,
                    errorRecord.ToString(),
                    errorRecord.InvocationInfo.PositionMessage,
                    errorRecord.CategoryInfo,
                    errorRecord.FullyQualifiedErrorId);

            this.WriteError(message);
        }
Example #10
0
 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());
 }
 public void WriteError(ErrorRecord errorRecord)
 {
     if (caller != null)
     {
         caller.WriteError(errorRecord);
     }
     else
     {
         OnOutput(new CallerProxyEventArgs()
         {
             StreamName = "Error", Text = errorRecord.ToString()
         });
     }
 }
Example #12
0
        private void WriteException(Exception exception)
        {
            string str;
            PSRemotingTransportException pSRemotingTransportException = exception as PSRemotingTransportException;

            if (pSRemotingTransportException == null || pSRemotingTransportException.InnerException as TargetInvocationException == null || pSRemotingTransportException.InnerException.InnerException == null)
            {
                IContainsErrorRecord containsErrorRecord = exception as IContainsErrorRecord;
                if (containsErrorRecord != null)
                {
                    ErrorRecord errorRecord = containsErrorRecord.ErrorRecord;
                    if (errorRecord.InvocationInfo == null || errorRecord.InvocationInfo.PositionMessage == null)
                    {
                        str = errorRecord.ToString();
                    }
                    else
                    {
                        str = errorRecord.InvocationInfo.PositionMessage;
                    }
                    string str1     = str;
                    char[] chrArray = new char[2];
                    chrArray[0] = '\n';
                    chrArray[1] = '\r';
                    str1        = str1.TrimEnd(chrArray);
                    this.WriteErrorLine(str1);
                    object[] categoryInfo = new object[1];
                    categoryInfo[0] = errorRecord.CategoryInfo;
                    this.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, "    + CategoryInfo          : {0} ", categoryInfo));
                    object[] fullyQualifiedErrorId = new object[1];
                    fullyQualifiedErrorId[0] = errorRecord.FullyQualifiedErrorId;
                    this.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, "    + FullyQualifiedErrorId : {0} ", fullyQualifiedErrorId));
                    this.WriteErrorLine("");
                    return;
                }
            }
            else
            {
                exception = pSRemotingTransportException.InnerException;
            }
            if (exception as TargetInvocationException == null)
            {
                this.host.UI.WriteErrorLine(exception.Message);
                return;
            }
            else
            {
                this.host.UI.WriteErrorLine(exception.InnerException.Message);
                return;
            }
        }
        public void WriteError(ErrorRecord record)
        {
            if (this.OnDifferentThread)
            {
                this.errorQueue.Enqueue(record);
            }
            else if (this.CommandRuntimeAvailable)
            {
                this.Cmdlet.WriteError(record);
                this.ErrorListener?.Invoke(record);
            }

            Trace.TraceError(record.ToString());
        }
 public static PsStreamEventHandlers GetUIHandlers(WorkerContext ctx) => new PsStreamEventHandlers()
 {
     Debug = (o, e) =>
     {
         DebugRecord newRecord = ((PSDataCollection <DebugRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     },
     Error = (o, ev) =>
     {
         ErrorRecord newRecord = ((PSDataCollection <ErrorRecord>)o)[ev.Index];
         MessageBox.Show(newRecord.ToString(), "Powershell Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     },
     Information = (o, e) =>
     {
         InformationalRecord newRecord = ((PSDataCollection <InformationalRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     },
     Progress = (o, ev) =>
     {
         ProgressRecord r = ((PSDataCollection <ProgressRecord>)o)[ev.Index];
         ctx.d.ReportCaption(r.Activity);
         if (r.PercentComplete >= 0 && r.PercentComplete <= 100)
         {
             ctx.d.ReportProgress(r.PercentComplete);
         }
     },
     Verbose = (o, e) =>
     {
         VerboseRecord newRecord = ((PSDataCollection <VerboseRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     },
     Warning = (o, e) =>
     {
         WarningRecord newRecord = ((PSDataCollection <WarningRecord>)o)[e.Index];
         if (!string.IsNullOrEmpty(newRecord.Message))
         {
             Program.MainFrmInstance.SetStatus(newRecord.Message);
         }
     }
 };
        private string GetErrorMessage(String functionName, ErrorRecord errorRecord)
        {
            var sb = new StringBuilder();

            if (!String.IsNullOrEmpty(functionName))
            {
                sb.Append(String.Format("[{0}] ", functionName));
            }
            sb.Append(errorRecord.ToString());
            if (errorRecord.InvocationInfo != null)
            {
                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());
            }
        }
Example #17
0
        private static string ErrorRecordToString(ErrorRecord error)
        {
            StringBuilder sb = new StringBuilder(error.ToString());

            if (error.ScriptStackTrace != null)
            {
                sb.AppendLine("");
                sb.AppendLine(error.ScriptStackTrace);
            }
            if (error.Exception != null && error.Exception.StackTrace != null)
            {
                sb.AppendLine("");
                sb.AppendLine(error.Exception.StackTrace.ToString());
            }

            return(sb.ToString());
        }
Example #18
0
        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());
        }
        private void RunTests(string describeName, string scenarioName, RunContext runContext)
        {
            runContext.UpdateRunningTest("All tests");

            string module = FindModule("Pester", runContext);

            _powerShell.AddCommand("Import-Module").AddParameter("Name", module);
            _powerShell.Invoke();
            _powerShell.Commands.Clear();

            if (_powerShell.HadErrors)
            {
                ErrorRecord errorRecord  = _powerShell.Streams.Error.FirstOrDefault();
                string      errorMessage = errorRecord?.ToString() ?? string.Empty;

                throw new Exception($"FailedToLoadPesterModule {errorMessage}");
            }

            RunTestFiles(describeName, runContext);

            RunTestScenarios(scenarioName, runContext);
        }
Example #20
0
        internal void LogExecutionError(InvocationInfo invocationInfo, ErrorRecord errorRecord)
        {
            if (errorRecord == null)
                return;

            string message = StringUtil.Format(PipelineStrings.PipelineExecutionNonTerminatingError, GetCommand(invocationInfo), errorRecord.ToString());
            Log(message, invocationInfo, PipelineExecutionStatus.Error);
        }
Example #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RunspaceException"/> class.
 /// </summary>
 /// <param name="error">The <see cref="ErrorRecord"/> that was written to the stream.</param>
 internal RunspaceException(ErrorRecord error)
     : base(error.ToString(), error.Exception)
 {
 }
 private void WriteErrorRecord(RemoteComputer powershellComputer, ErrorRecord record)
 {
     powershellComputer.AddLogEntry(new LogEntry(powershellComputer.Name, record.ToString(), LogEntryType.Error));
 }
Example #23
0
        private bool InternalExecuteScript(string script, bool handleError, int subSteps, LocalizedString statusDescription)
        {
            bool     result   = false;
            WorkUnit workUnit = new WorkUnit();
            bool     newSubProgressReceived = false;
            int      completedSubSteps      = 0;

            try
            {
                script.TrimEnd(new char[]
                {
                    '\n'
                });
                string script2 = script.Replace("\n", "\r\n");
                if (handleError)
                {
                    base.WriteVerbose(Strings.ExecutingScriptNonFatal(script2));
                }
                else
                {
                    base.WriteVerbose(Strings.ExecutingScript(script2));
                }
                script = string.Format("$error.Clear(); {0}", script);
                MonadCommand monadCommand = new MonadCommand(script, this.monadConnection);
                monadCommand.CommandType     = CommandType.Text;
                monadCommand.ProgressReport += delegate(object sender, ProgressReportEventArgs e)
                {
                    if (subSteps == 0)
                    {
                        return;
                    }
                    completedSubSteps      = subSteps * e.ProgressRecord.PercentComplete / 100;
                    newSubProgressReceived = true;
                };
                bool flag = false;
                try
                {
                    TaskLogger.IncreaseIndentation();
                    TaskLogger.LogErrorAsWarning = handleError;
                    MonadAsyncResult monadAsyncResult = monadCommand.BeginExecute(new WorkUnit[]
                    {
                        workUnit
                    });
                    while (!flag)
                    {
                        flag = monadAsyncResult.AsyncWaitHandle.WaitOne(200, false);
                        if (newSubProgressReceived)
                        {
                            base.WriteProgress(this.Description, statusDescription, (this.completedSteps + completedSubSteps) * 100 / this.totalSteps);
                            newSubProgressReceived = false;
                        }
                        if (base.Stopping)
                        {
                            break;
                        }
                    }
                    if (base.Stopping)
                    {
                        monadCommand.Cancel();
                    }
                    else
                    {
                        monadCommand.EndExecute(monadAsyncResult);
                    }
                }
                catch (CommandExecutionException ex)
                {
                    if (ex.InnerException != null)
                    {
                        throw new ScriptExecutionException(Strings.ErrorCommandExecutionException(script, ex.InnerException.ToString()), ex.InnerException);
                    }
                    throw;
                }
                finally
                {
                    TaskLogger.DecreaseIndentation();
                }
                this.completedSteps += subSteps;
                result = true;
            }
            catch (CmdletInvocationException ex2)
            {
                result = false;
                if (!handleError)
                {
                    throw;
                }
                base.WriteVerbose(Strings.IgnoringException(ex2.ToString()));
                base.WriteVerbose(Strings.WillContinueProcessing);
            }
            if (workUnit.Errors.Count > 0)
            {
                result = false;
                int count = workUnit.Errors.Count;
                base.WriteVerbose(Strings.ErrorDuringTaskExecution(count));
                for (int i = 0; i < count; i++)
                {
                    ErrorRecord errorRecord = workUnit.Errors[i];
                    base.WriteVerbose(Strings.ErrorRecordReport(errorRecord.ToString(), i));
                    if (!handleError)
                    {
                        base.WriteVerbose(Strings.ErrorRecordReport(errorRecord.Exception.ToString(), i));
                        ScriptExecutionException exception = new ScriptExecutionException(Strings.ErrorCommandExecutionException(script, errorRecord.Exception.ToString()), errorRecord.Exception);
                        this.WriteError(exception, errorRecord.CategoryInfo.Category, errorRecord.TargetObject, false);
                    }
                }
                if (handleError)
                {
                    base.WriteVerbose(Strings.WillIgnoreNoncriticalErrors);
                    base.WriteVerbose(Strings.WillContinueProcessing);
                }
            }
            return(result);
        }
        public Collection <T> RunPSCommand <T>(PSCommand command) where T : class
        {
            ErrorRecord errorRecord   = null;
            string      commandString = AnchorRunspaceProxy.GetCommandString(command);

            try
            {
                Collection <T> result = this.RunPSCommand <T>(command, out errorRecord);
                if (errorRecord == null)
                {
                    this.Context.Logger.Log(MigrationEventType.Verbose, "Running PS command {0}", new object[]
                    {
                        commandString
                    });
                    return(result);
                }
            }
            catch (ParameterBindingException ex)
            {
                this.HandleException <T>(commandString, ex);
            }
            catch (CmdletInvocationException ex2)
            {
                this.HandleException <T>(commandString, ex2);
            }
            AnchorUtil.AssertOrThrow(errorRecord != null, "expect to have an error at this point", new object[0]);
            if (errorRecord.Exception != null)
            {
                this.HandleException <T>(commandString, errorRecord.Exception);
            }
            throw new MigrationPermanentException(ServerStrings.MigrationRunspaceError(commandString, errorRecord.ToString()));
        }
 void IOutputWriter.ThrowTerminatingError(ErrorRecord record)
 {
     this.consoleHost?.WriteOutput(record.ToString(), true, OutputType.Error, ConsoleColor.Red, ConsoleColor.Black);
 }
 void IOutputWriter.WriteError(ErrorRecord error)
 {
     this.consoleHost?.WriteOutput(error.ToString(), true, OutputType.Error, ConsoleColor.Red, ConsoleColor.Black);
 }
Example #27
0
        /// <summary>
        /// Sets up the PowerShell shell stream event handlers.
        /// </summary>
        /// <param name="shell">The PowerShell shell.</param>
        private static void SetupStreamEventHandlers(PowerShell shell)
        {
            Logger.Instance.WriteMethodEntry(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers);

            try
            {
                shell.Streams.ClearStreams();
                shell.Streams.Error.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <ErrorRecord> errorStream = (PSDataCollection <ErrorRecord>)sender;
                    ErrorRecord record = errorStream[e.Index];
                    if (record == null)
                    {
                        return;
                    }

                    StringBuilder builder = new StringBuilder();
                    builder.AppendLine(record.ToString());

                    if (record.InvocationInfo != null)
                    {
                        builder.AppendLine();
                        builder.AppendLine(record.InvocationInfo.PositionMessage);
                    }

                    Logger.Instance.WriteError(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersErrorEvents, builder.ToString());
                };
                shell.Streams.Warning.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <WarningRecord> warningStream = (PSDataCollection <WarningRecord>)sender;
                    WarningRecord record = warningStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteWarning(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersWarningEvents, record.ToString());
                    }
                };
                shell.Streams.Debug.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <DebugRecord> debugStream = (PSDataCollection <DebugRecord>)sender;
                    DebugRecord record = debugStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersDebugEvents, record.ToString());
                    }
                };
                shell.Streams.Verbose.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <VerboseRecord> versboseStream = (PSDataCollection <VerboseRecord>)sender;
                    VerboseRecord record = versboseStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteVerbose(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersEvents, record.ToString());
                    }
                };
                shell.Streams.Progress.DataAdded += delegate(object sender, DataAddedEventArgs e)
                {
                    PSDataCollection <ProgressRecord> progressStream = (PSDataCollection <ProgressRecord>)sender;
                    ProgressRecord record = progressStream[e.Index];
                    if (record != null)
                    {
                        Logger.Instance.WriteInfo(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlersProgressEvents, record.ToString());
                    }
                };
            }
            finally
            {
                Logger.Instance.WriteMethodExit(EventIdentifier.RunPowerShellScriptSetupStreamEventHandlers);
            }
        }
Example #28
0
 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);
     }
 }
        public IExecutionResult Execute(string script)
        {
            var result = new ExecutionResult();

            try
            {
                var pipeline = Runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);

                var output = pipeline.Invoke();

                if (pipeline.Error.Count > 0)
                {
                    foreach (object error in pipeline.Error.ReadToEnd())
                    {
                        var pso = error as PSObject;
                        if (pso == null)
                        {
                            continue;
                        }
                        ErrorRecord errorRecord = pso.BaseObject as ErrorRecord;
                        Exception   ex;

                        if (errorRecord != null)
                        {
                            if (result.Error == null)
                            {
                                result.Error = new ErrorResult()
                                {
                                    Name    = errorRecord.FullyQualifiedErrorId,
                                    Message = string.Format(
                                        "{0} : {1}\n{2}\n    + CategoryInfo          : {3}\n    + FullyQualifiedErrorId : {4}",
                                        errorRecord.InvocationInfo.InvocationName,
                                        errorRecord.ToString(),
                                        errorRecord.InvocationInfo.PositionMessage,
                                        errorRecord.CategoryInfo,
                                        errorRecord.FullyQualifiedErrorId),
                                    StackTrace = errorRecord.ScriptStackTrace.Split(new [] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList()
                                };
                            }
                            ex = errorRecord.Exception;
                        }
                        else
                        {
                            ex = pso.BaseObject as Exception;
                        }

                        if (ex != null)
                        {
                            result.Exceptions.Add(ex);
                        }
                    }
                }

                if (output.Count > 0)
                {
                    result.Output.AddRange(output.Select(o => o.BaseObject));
                    pipeline = Runspace.CreatePipeline();
                    var formatter = new Command("Out-String");
                    pipeline.Commands.Add(formatter);

                    result.OutputString = string.Join("\n", pipeline.Invoke(output).Select(line => line.ToString())).Trim();

                    //pipeline = Runspace.CreatePipeline();
                    //formatter = new Command("ConvertTo-Json");
                    //pipeline.Commands.Add(formatter);
                    //result.OutputJson = string.Join("\n", pipeline.Invoke(JsonWrapper.Wrap(script, output)).Select(line => line.ToString().Replace("\r\n","\n")));

                    // Users need to output their own HTML, ConvertTo-Html is *way* too flawed.
                    // BUGBUG: need a better way to detect html?
                    if (output.First().BaseObject is string && result.OutputString.StartsWith("<") && result.OutputString.EndsWith(">"))
                    {
                        result.OutputHtml = result.OutputString;
                    }
                }
                // result.OutputJson = JsonConvert.SerializeObject(output);

                //var teeCommand = new Command("Tee-Object");
                //teeCommand.Parameters.Add("-Variable", "Output");
                //pipeline.Commands.Add(teeCommand);

                //var htmlCommand = new Command("ConvertTo-Html");
                //htmlCommand.Parameters.Add("-Fragment");
                //pipeline.Commands.Add(htmlCommand);
            }
            catch (Exception ex)
            {
                _logger.LogError("PowerShell Exception in ExecuteRequest {0}:\r\n{1}\r\n{2}", script, ex.Message, ex.StackTrace);
                result.Exceptions.Add(ex);
            }

            return(result);
        }
 public void ThrowTerminatingError(ErrorRecord record)
 {
     Trace.TraceError(record.ToString());
     this.ErrorListener?.Invoke(record);
     this.Cmdlet.ThrowTerminatingError(record);
 }
Example #31
0
        // .\WMIMon.exe "[-filter=regularexpression]" "[-stop=[start|end|none]]"   [-log=all|filter] [-action=powershellpipeline]]
        static void Main(string[] args)
        {
            string filter = "";

            StopCondition uStop        = StopCondition.none;
            bool          LogOnFilter  = true;
            UInt64        IfStopStatus = 0;
            bool          bAction      = false;
            string        PipeLine     = "";
            Runspace      runSpace     = RunspaceFactory.CreateRunspace();

            runSpace.Open();

            Dictionary <UInt64, string> PendingOp = new Dictionary <UInt64, string>();



            foreach (string arg in args)
            {
                Match m;

                m = Regex.Match(arg, "-(f|fi|fil|filt|filt|filte|filter)=(.+)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    filter = m.Groups[2].ToString().ToLower();
                    Console.WriteLine("Parsing:\tfiltering on {0}", filter);
                    if (!IsValidRegex(filter))
                    {
                        Console.WriteLine("Parsing:\tInvalid regular expression {0}", filter);
                        return;
                    }
                    continue;
                }

                m = Regex.Match(arg, "-(s|st|sto|stop)=(start|end|none)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    string stop = m.Groups[2].ToString().ToLower();
                    uStop = StopCondition.none;
                    if (stop == "start")
                    {
                        uStop = StopCondition.start;
                    }
                    else if (stop == "end")
                    {
                        uStop = StopCondition.stop;
                    }
                    Console.WriteLine("Parsing:\twill stop if filter matches {0}", stop);
                    continue;
                }
                m = Regex.Match(arg, "-(l|lo|log)=(all|filter)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    string log = m.Groups[2].ToString().ToLower();
                    Console.WriteLine("Parsing:\tlogging option : {0} ", log);
                    if (log == "all")
                    {
                        LogOnFilter = false;
                    }
                    else
                    {
                        LogOnFilter = true;
                    }


                    continue;
                }
                m = Regex.Match(arg, "-(i|if|ifs|ifsto|ifstop|ifstops|ifstopst|ifstopstat|ifstopstatu|ifstopstatus)=(0x[0-9,a-f]+|[0-9,a-f]+)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    // bAction = true;
                    IfStopStatus = Convert.ToUInt64(m.Groups[2].ToString(), 16);
                    Console.WriteLine("Parsing:\tPowershell will end if status is : 0x{0:x} ", IfStopStatus);
                    continue;
                }

                m = Regex.Match(arg, "-(a|ac|act|acti|actio|action)=(.+)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    bAction  = true;
                    PipeLine = m.Groups[2].ToString();
                    Console.WriteLine("Parsing:\tPowershell action when filter is found : {0} ", PipeLine);
                }
                else
                {
                    Console.WriteLine("Parsing:\tInvalid argument {0}\n", arg);
                    Console.WriteLine(
                        @"
Usage:  WmiMon [-filter=regular_expression_string] [-stop=start|end|none] [-ifstopstatus=hexadecimal_value] [-log=all|filter] [action=pipeline]
                  default WmiMon [-filter=.*] [-stop=none] [-log=all]

will monitor WMI activity. By default all WMI activities are displayed. 

You can filter the output with the -filter switch.

You can stop the application :
- if the filtering is successfull. Stop will occur at activity startup  if -stop=start is specified.
      If -stop=end is specified we will wait for the end of the activity to stop the monitoring
        Warning : if many records match the filtering pattern , memory usage  may increase  
- if the filtering is successfull and _ifstopstatus condition is meet
    Warning : if many records match the filtering pattern , memory usage for this query may be hudge  

For all filtered items or if a stop condition is meet , the pipeline action will be executed         
Powershell variables WMIMON_* will be set in Powershell runspace to reflect the current WMI activity.
Your Powershell actions may use these variables (client PID, client computer, client user, stop status, WMI query,...)  

N.B: WMIMon is based on RealTime ETL notification. ETL infrastructure doesn't guarantee that all events will be received.
N.B: WMI Stop operation logging may occur after a delay based on client (get-cim* cmdlets cleanup occurs immediately 
     This is not true with get-wmiobject cmdlet).

Feel Free to report any bug or suggestion to [email protected]

Example: 
"

                        );

                    return;
                }
            }

            var exitEvent = new ManualResetEvent(false);

            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                eventArgs.Cancel = true;
                exitEvent.Set();
            };


            NotifyCallback Notify = (string OutStr, bool bError) =>
            {
                if (bError)
                {
                    Console.WriteLine("******! Error  {0}", OutStr);
                }
                else
                {
                    Console.WriteLine("***** {0}", OutStr);
                }
            };
            GetResultCallBack Result = (string OutStr, UInt32 GroupId, UInt32 OpId) =>
            {
                bool   bDisplay        = true;
                bool   bStopOperation  = false;
                UInt64 StopStatus      = 0;
                string ClientProcessId = "";
                string Executable      = "";
                string Computer        = "";
                string User            = "";
                bool   bFilter         = (filter.Length != 0) ? true : false;
                bool   bFilterMatch    = false;
                bool   bStop           = false;

                string PendingQuery = "";
                bool   bDisplayStop = false;

                Match m;
                m = Regex.Match(OutStr, "^\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d Stop Op=\\d+ 0x([0-9a-fA-F]+)", RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    bStopOperation = true;
                    bDisplayStop   = true;
                    StopStatus     = Convert.ToUInt64(m.Groups[1].ToString(), 16);


                    if (bFilter)
                    {
                        bDisplayStop = false;

                        //is this operation in the Pending list
                        if (PendingOp.TryGetValue(OpId, out PendingQuery))
                        {
                            m = Regex.Match(PendingQuery, "^\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d .* _ClientProcessId=(\\d+) \\[(.*)\\] (.*) (.*) ", RegexOptions.IgnoreCase);
                            if (m.Success)
                            {
                                ClientProcessId = m.Groups[1].ToString();
                                Executable      = m.Groups[2].ToString();
                                Computer        = m.Groups[3].ToString();
                                User            = m.Groups[4].ToString();
                                bDisplayStop    = true;
                            }
                            PendingOp.Remove(OpId);
                            if ((IfStopStatus != 0) && (StopStatus == IfStopStatus))
                            {
                                bStop = true;
                            }
                            else if (StopCondition.stop == uStop)
                            {
                                bStop = true;
                            }
                            // Console.WriteLine("==== Debug : Removing Pending Stop {0} \\ {1}\\ bStop {2} ", OutStr, PendingQuery , bStop );
                        }
                    }
                }
                else
                {
                    bStopOperation = false;
                    m = Regex.Match(OutStr, "^\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d .* _ClientProcessId=(\\d+) \\[(.*)\\] (.*) (.*) ", RegexOptions.IgnoreCase);
                    if (m.Success)
                    {
                        ClientProcessId = m.Groups[1].ToString();
                        Executable      = m.Groups[2].ToString();
                        Computer        = m.Groups[3].ToString();
                        User            = m.Groups[4].ToString();
                    }
                }
                if (!bStopOperation)
                {
                    if (bFilter)
                    {
                        string          outwithoutn = OutStr.Replace("\n", "");
                        MatchCollection mFilter     = Regex.Matches(outwithoutn, filter, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                        if (mFilter.Count > 0)
                        {
                            bFilterMatch = true;
                        }
                    }
                }
                // at this point
                // bFilter ==> if filter
                // bFilterMatch ==> if filter match
                // bLogFilter ==> true -log=filter
                //            ==> false -log=all
                // uStop ==> StopCondition.none , StopCondition.start , StopCondition.end
                // bAction == TRUE ==> pipeline
                bDisplay = false;

                if (bFilter)
                {
                    bDisplay = false;
                    if (bFilterMatch && LogOnFilter == true)
                    {
                        bDisplay = true;
                    }
                    else if (LogOnFilter == false)
                    {
                        bDisplay = true;
                    }
                    if (uStop == StopCondition.start && bFilterMatch)
                    {
                        bStop = true;
                    }
                    else if (uStop == StopCondition.stop && bFilterMatch)
                    {
                        // TODO : add to stoppending list
                    }
                    if (bFilter && bFilterMatch)
                    {
                        PendingOp.Add(OpId, OutStr);
                        // Console.WriteLine("==== Debug Adding {0} in Pending list ", OpId);
                    }
                }
                else
                {
                    bDisplay = true;
                }
                if (bDisplay || bDisplayStop)
                {
                    Console.WriteLine("***** {0}", OutStr);
                }

                if ((bAction && bFilter && bFilterMatch) | (bStop && bFilter))
                {
                    // TODO Execute Pipeline
                    runSpace.SessionStateProxy.SetVariable("WMIMON_PID", ClientProcessId);
                    runSpace.SessionStateProxy.SetVariable("WMIMON_EXECUTABLE", Executable);
                    runSpace.SessionStateProxy.SetVariable("WMIMON_COMPUTER", Computer);
                    runSpace.SessionStateProxy.SetVariable("WMIMON_USER", User);
                    runSpace.SessionStateProxy.SetVariable("WMIMON_STOPSTATUS", StopStatus);
                    runSpace.SessionStateProxy.SetVariable("WMIMON_ACTIVITY", OutStr);
                    runSpace.SessionStateProxy.SetVariable("WMIMON_RELATEDACTIVITY", PendingQuery);
                    Pipeline pipeline = runSpace.CreatePipeline();
                    String   script   = PipeLine + " | out-string ";
                    pipeline.Commands.AddScript(script);

                    Collection <PSObject> Results;
                    try
                    {
                        Results = pipeline.Invoke();
                        foreach (PSObject PsObj  in Results)
                        {
                            Console.WriteLine(PsObj.ToString());
                        }
                    }
                    catch (PSInvalidOperationException ioe)
                    {
                        Console.WriteLine("Powershell Error: " + ioe.Message);
                        pipeline.Stop();
                        pipeline = null;
                    }
                    catch (System.Management.Automation.RuntimeException error)
                    {
                        ErrorRecord e = error.ErrorRecord;
                        Console.WriteLine("Powershell Error: {0}{1} ", e.ToString(), e.InvocationInfo.PositionMessage);
                        pipeline.Stop();
                        pipeline = null;
                    }
                }

                if (bStop)
                {
                    exitEvent.Set();
                }
            };

            IntPtr Context = (IntPtr)1;
            IntPtr Handle  = exitEvent.SafeWaitHandle.DangerousGetHandle();

            try
            {
                StartAndWait((IntPtr)Handle, Context, Notify, Result); // cf https://msdn.microsoft.com/en-us/library/7esfatk4(VS.71).aspx
            }
            catch (SystemException e)
            {
                Console.WriteLine("Unexpected error {0} ", e);
            }
        }