Ejemplo n.º 1
0
        /// <summary>
        /// StartJob
        /// </summary>
        public override void StartJob()
        {
            if (this.JobStateInfo.State != JobState.NotStarted)
            {
                throw new Exception(Properties.Resources.CannotStartJob);
            }

            // Initialize Runspace state
            _rs.Open();

            // Set current location path on the runspace, if available.
            if (_currentLocationPath != null)
            {
                using (var ps = System.Management.Automation.PowerShell.Create())
                {
                    ps.Runspace = _rs;
                    ps.AddCommand("Set-Location").AddParameter("LiteralPath", _currentLocationPath).Invoke();
                }
            }

            // If initial script block provided then execute.
            if (_initSb != null)
            {
                // Run initial script and then the main script.
                _ps.Commands.Clear();
                _ps.AddScript(_initSb.ToString());
                _runningInitScript = true;
                _ps.BeginInvoke <object, PSObject>(_input, _output);
            }
            else
            {
                // Run main script.
                RunScript();
            }
        }
Ejemplo n.º 2
0
        private Task RunScriptToOutputAsync(string script, CancellationToken cancellation)
        {
            shell.Runspace = host.Runspace;
            shell.AddScript(script);
            shell.AddCommand("Out-Default");
            //shell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

            shell.Streams.Error.DataAdded   += Error_DataAdded;
            shell.Streams.Warning.DataAdded += Warning_DataAdded;
            shell.Streams.Verbose.DataAdded += Verbose_DataAdded;
            shell.Streams.Debug.DataAdded   += Debug_DataAdded;
            //shell.Streams.Information.DataAdded += Information_DataAdded;

            cancellationTask = CheckForCancellation(cancellation);

            return(Task.Factory.FromAsync(shell.BeginInvoke(), (result) =>
            {
                //var output = shell.EndInvoke(result);
                resultBuilder.Finish();
                resultBuilder.Stream.NotifyAboutCompletion();

                shell.Streams.Error.DataAdded -= Error_DataAdded;
                shell.Streams.Warning.DataAdded -= Warning_DataAdded;
                shell.Streams.Verbose.DataAdded -= Verbose_DataAdded;
                shell.Streams.Debug.DataAdded -= Debug_DataAdded;
                //shell.Streams.Information.DataAdded -= Information_DataAdded;
                ReleaseShell();
            }));
        }
        /// <summary>
        /// Invoke script with parameters.
        /// </summary>
        /// <param name="script">Script command to be invoked.</param>
        /// <param name="parameters">Parameters for the command.</param>
        public void InvokeAsync(string script, params PowerShellScriptParameter[] parameters)
        {
            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.AddScript(script);

                if (parameters != null)
                {
                    foreach (var parameter in parameters)
                    {
                        powerShell.AddParameter(parameter.Name, parameter.Value);
                    }
                }

                // begin invoke execution on the pipeline
                IAsyncResult result = powerShell.BeginInvoke();

                // do something else until execution has completed.
                // this could be sleep/wait, or perhaps some other work
                while (!result.IsCompleted)
                {
                    Thread.Sleep(1000);
                }

                this.logger.LogDebug("Execution has stopped. The pipeline state: " + powerShell.InvocationStateInfo.State);
            }
        }
Ejemplo n.º 4
0
        private Task <IEnumerable <PSObject> > RunIndependentCommandAsync(string input)
        {
            independentShell.Runspace = host.GetIndependentRunspace();
            independentShell.AddScript(input);

            return(Task.Factory.FromAsync <IEnumerable <PSObject> >(independentShell.BeginInvoke(), (result) =>
            {
                return independentShell.EndInvoke(result);
            }));
        }
        public static async Task <PSDataCollection <T2> > InvokeAsync <T1, T2>(this System.Management.Automation.PowerShell shell, PSDataCollection <T1> input = null, PSInvocationSettings invocationSettings = null)
        {
            var    output = new PSDataCollection <T2>();
            object state  = "none";

            await Task.Factory.FromAsync(
                (t1, t2, callback, obj) => shell.BeginInvoke(t1, t2, invocationSettings ?? new PSInvocationSettings(), callback, obj),
                (Action <IAsyncResult>)((a) => shell.EndInvoke(a)), input, output, state);

            return(output);
        }
Ejemplo n.º 6
0
        void ExecuteScriptBlock()
        {
            PSDataCollection <PSObject> data = new PSDataCollection <PSObject>();

            data.DataAdded += (s, a) =>
            {
                PSObject ps = data[a.Index];
                AddDataObject(ps);
            };

            var input = CurrentScriptBlockInput;

            _asyncResult = _powerShell.BeginInvoke(input, data);
        }
        /// <summary>
        /// Sample execution scenario 2: Asynchronous.
        /// </summary>
        /// <param name="script">Script command to be invoked.</param>
        /// <param name="parameters">Parameters for the command.</param>
        /// <remarks>
        /// Executes a PowerShell script asynchronously with script output and event handling.
        /// </remarks>
        public void ExecuteAsynchronously(string script, params PowerShellScriptParameter[] parameters)
        {
            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.AddScript(script);

                if (parameters != null)
                {
                    foreach (var parameter in parameters)
                    {
                        powerShell.AddParameter(parameter.Name, parameter.Value);
                    }
                }

                // prepare a new collection to store output stream objects
                PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();
                outputCollection.DataAdded += this.OutputCollection_DataAdded;

                // the streams (Error, Debug, Progress, etc) are available on the PowerShell instance.
                // we can review them during or after execution.
                // we can also be notified when a new item is written to the stream (like this):
                powerShell.Streams.Error.DataAdded += this.Error_DataAdded;

                // begin invoke execution on the pipeline
                // use this overload to specify an output stream buffer
                IAsyncResult result = powerShell.BeginInvoke <PSObject, PSObject>(null, outputCollection);

                // do something else until execution has completed.
                // this could be sleep/wait, or perhaps some other work
                while (!result.IsCompleted)
                {
                    Thread.Sleep(1000);
                }

                this.logger.LogDebug("Execution has stopped. The pipeline state: " + powerShell.InvocationStateInfo.State);

                foreach (var outputItem in outputCollection)
                {
                    if (outputItem != null)
                    {
                        this.logger.LogDebug(outputItem.BaseObject.GetType().FullName);
                        this.logger.LogDebug(outputItem.BaseObject.ToString() + "\n");
                    }
                }

                this.ProcessPowerShellStreams(powerShell);
                outputCollection.Dispose();
            }
        }
Ejemplo n.º 8
0
        public void Run(List <string> Commands)
        {
            try
            {
                if (Commands?.Count > 0)
                {
                    using (runSpace = RunspaceFactory.CreateRunspace())
                    {
                        runSpace.Open();

                        using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                        {
                            pwsh.Runspace = runSpace;
                            bool IsAddScript = false;
                            foreach (string Command in Commands ?? Enumerable.Empty <string>())
                            {
                                if (!string.IsNullOrEmpty(Command))
                                {
                                    pwsh.AddScript(Command);
                                    IsAddScript = true;
                                }
                            }

                            if (IsAddScript)
                            {
                                IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();
                                _ = pwsh.EndInvoke(gpcAsyncResult);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }
        }
        private async Task<PSDataCollection<ErrorRecord>> InvokePowerShellScript(Dictionary<string, string> envVars, TraceWriter traceWriter)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            PSDataCollection<ErrorRecord> errors = new PSDataCollection<ErrorRecord>();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
            {
                runspace.Open();
                SetRunspaceEnvironmentVariables(runspace, envVars);
                RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
                runSpaceInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");

                using (
                    System.Management.Automation.PowerShell powerShellInstance =
                        System.Management.Automation.PowerShell.Create())
                {
                    powerShellInstance.Runspace = runspace;
                    _moduleFiles = GetModuleFilePaths(_host.ScriptConfig.RootScriptPath, _functionName);
                    if (_moduleFiles.Any())
                    {
                        powerShellInstance.AddCommand("Import-Module").AddArgument(_moduleFiles);
                        LogLoadedModules();
                    }

                    _script = GetScript(_scriptFilePath);
                    powerShellInstance.AddScript(_script, true);

                    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
                    outputCollection.DataAdded += (sender, e) => OutputCollectionDataAdded(sender, e, traceWriter);

                    powerShellInstance.Streams.Error.DataAdded += (sender, e) => ErrorDataAdded(sender, e, traceWriter);

                    IAsyncResult result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
                    await Task.Factory.FromAsync<PSDataCollection<PSObject>>(result, powerShellInstance.EndInvoke);

                    foreach (ErrorRecord errorRecord in powerShellInstance.Streams.Error)
                    {
                        errors.Add(errorRecord);
                    }
                }

                runspace.Close();
            }

            return errors;
        }
Ejemplo n.º 10
0
        public void AysncSynchronousPipline(int who = 0)
        {
            if (ps != null)
            {
                IAsyncResult async = ps.BeginInvoke();

                ps.Runspace.Debugger.DebuggerStop += Debugger_DebuggerStop;



                foreach (PSObject result in ps.EndInvoke(async))
                {
                    if (result != null)
                    {
                        output.Add(result.BaseObject);
                    }
                }
            }
        }
Ejemplo n.º 11
0
        public Task <PSDataCollection <PSObject> > Start()
        {
            if (_powerShell.InvocationStateInfo.State == PSInvocationState.NotStarted)
            {
                if (_powerShell == null)
                {
                    throw new ArgumentNullException();
                }

                try
                {
                    return(Task.Factory.FromAsync(_powerShell.BeginInvoke <PSObject, PSObject>(null, _outputCollection), EndInvoke));
                }
                catch (InvalidRunspaceStateException e)
                {
                    if (e.CurrentState == RunspaceState.Broken)
                    {
                        throw new RemoteTimeoutException("Remote operation timed out. Please check remote host availability");
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// This sample shows how to use a PowerShell object to run a
        /// script that generates the numbers from 1 to 10 with delays
        /// between each number. The pipeline of the PowerShell object
        /// is run asynchronously and events are used to handle the output.
        /// </summary>
        /// <param name="args">This parameter is not used.</param>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating a PowerShell object.
        /// 2. Adding a script to the pipeline of the PowerShell object.
        /// 3. Using the BeginInvoke method to run the pipeline asynchronosly.
        /// 4. Using the events of the PowerShell object to process the
        ///    output of the script.
        /// 5. Using the PowerShell.Stop() method to interrupt an executing pipeline.
        /// </remarks>
        private static void Main(string[] args)
        {
            Console.WriteLine("Print the numbers from 1 to 10. Hit any key to halt processing\n");

            using (PowerShell powershell = PowerShell.Create())
            {
                // Add a script to the PowerShell object. The script generates the
                // numbers from 1 to 10 in half second intervals.
                powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}");

                // Add the event handlers.  If we did not care about hooking the DataAdded
                // event, we would let BeginInvoke create the output stream for us.
                PSDataCollection <PSObject> output = new PSDataCollection <PSObject>();
                output.DataAdded += new EventHandler <DataAddedEventArgs>(Output_DataAdded);
                powershell.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(Powershell_InvocationStateChanged);

                // Invoke the pipeline asynchronously.
                IAsyncResult asyncResult = powershell.BeginInvoke <PSObject, PSObject>(null, output);

                // Wait for things to happen. If the user hits a key before the
                // script has completed, then call the PowerShell Stop() method
                // to halt processing.
                Console.ReadKey();
                if (powershell.InvocationStateInfo.State != PSInvocationState.Completed)
                {
                    // Stop the execution of the pipeline.
                    Console.WriteLine("\nStopping the pipeline!\n");
                    powershell.Stop();

                    // Wait for the Windows PowerShell state change messages to be displayed.
                    System.Threading.Thread.Sleep(500);
                    Console.WriteLine("\nPress a key to exit");
                    Console.ReadKey();
                }
            }
        }
Ejemplo n.º 13
0
        public void Run(string Command)
        {
            string[] PrintCommandLines = Command.Split(new string[] { "\n" }, StringSplitOptions.None);

            //NCCFramework.Util.Logger.Debug(ref logger, $@"실행전 : Command = {string.Join("\r\n", PrintCommandLines)} / Now : {DateTime.Now}");

            try
            {
                using (runSpace = RunspaceFactory.CreateRunspace())
                {
                    runSpace.Open();

                    using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                    {
                        pwsh.Runspace = runSpace;
                        pwsh.AddScript(Command);
                        IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();
                        _ = pwsh.EndInvoke(gpcAsyncResult);
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }
        }
Ejemplo n.º 14
0
        public DataTable Run_Table(List <string> Commands)
        {
            DataTable _ret = new DataTable();

            try
            {
                using (runSpace = RunspaceFactory.CreateRunspace())
                {
                    runSpace.Open();

                    using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                    {
                        pwsh.Runspace = runSpace;

                        bool IsAddScript = false;
                        foreach (string Command in Commands ?? Enumerable.Empty <string>())
                        {
                            if (!string.IsNullOrEmpty(Command))
                            {
                                pwsh.AddScript(Command);
                                IsAddScript = true;
                            }
                        }

                        if (IsAddScript)
                        {
                            IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();

                            using (PSDataCollection <PSObject> ps_result = pwsh.EndInvoke(gpcAsyncResult))
                            {
                                foreach (PSObject psObject in ps_result)
                                {
                                    // Manual(수동풀) 일시 psObject value == Null
                                    if (psObject != null)
                                    {
                                        DataRow row = _ret.NewRow();
                                        foreach (PSPropertyInfo prop in psObject.Properties)
                                        {
                                            if (prop != null)
                                            {
                                                if (prop.TypeNameOfValue.ToUpper().Contains("STRING[]"))
                                                {
                                                    if (!_ret.Columns.Contains(prop.Name))
                                                    {
                                                        _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                                    }
                                                    string temp_prop_value = string.Empty;

                                                    for (int temp_i = 0; prop.Value != null && temp_i < ((string[])prop.Value).Length; temp_i++)
                                                    {
                                                        temp_prop_value += ((string[])prop.Value)[temp_i] + ", ";
                                                    }

                                                    if (temp_prop_value.EndsWith(", "))
                                                    {
                                                        temp_prop_value = temp_prop_value.Substring(0, temp_prop_value.Length - 2);
                                                    }

                                                    row[prop.Name] = temp_prop_value;
                                                }
                                                else if (prop.TypeNameOfValue.ToUpper().Contains("DICTIONARY"))
                                                {
                                                    if (!_ret.Columns.Contains(prop.Name))
                                                    {
                                                        _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                                    }
                                                    string temp_prop_value = string.Empty;

                                                    row[prop.Name] = temp_prop_value;
                                                }
                                                else if (prop.TypeNameOfValue.ToUpper().Contains("NULLABLE"))
                                                {
                                                    if (!_ret.Columns.Contains(prop.Name))
                                                    {
                                                        _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                                    }

                                                    try
                                                    {
                                                        row[prop.Name] = (prop.Value == null) ? "" : prop.Value;
                                                    }
                                                    catch
                                                    {
                                                        row[prop.Name] = "";
                                                    }
                                                }
                                                else if (prop.TypeNameOfValue.ToUpper().Contains("INT"))
                                                {
                                                    if (!_ret.Columns.Contains(prop.Name))
                                                    {
                                                        _ret.Columns.Add(new DataColumn(prop.Name, typeof(long)));
                                                    }

                                                    row[prop.Name] = prop.Value;
                                                }
                                                else
                                                {
                                                    if (!_ret.Columns.Contains(prop.Name))
                                                    {
                                                        _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                                    }

                                                    try
                                                    {
                                                        row[prop.Name] = (prop.Value == null) ? "" : prop.Value;
                                                    }
                                                    catch
                                                    {
                                                        row[prop.Name] = "";
                                                    }
                                                }
                                            }
                                        }
                                        _ret.Rows.Add(row);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }

            return(_ret);
        }
Ejemplo n.º 15
0
        public DataTable Run_Table(string Command)
        {
            string[] PrintCommandLines = Command.Split(new string[] { "\n" }, StringSplitOptions.None);

            //NCCFramework.Util.Logger.Debug(ref logger, $@"실행전 : Command = {string.Join("\r\n", PrintCommandLines)} / Now : {DateTime.Now}");

            DataTable _ret = new DataTable();

            try
            {
                using (runSpace = RunspaceFactory.CreateRunspace())
                {
                    runSpace.Open();

                    using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                    {
                        pwsh.Runspace = runSpace;
                        pwsh.AddScript(Command);
                        IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();

                        using (PSDataCollection <PSObject> ps_result = pwsh.EndInvoke(gpcAsyncResult))
                        {
                            foreach (PSObject psObject in ps_result)
                            {
                                DataRow row = _ret.NewRow();

                                foreach (PSPropertyInfo prop in psObject.Properties)
                                {
                                    if (prop != null)
                                    {
                                        if (prop.TypeNameOfValue.ToUpper().Contains("STRING[]"))
                                        {
                                            if (!_ret.Columns.Contains(prop.Name))
                                            {
                                                _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                            }
                                            string temp_prop_value = string.Empty;

                                            for (int temp_i = 0; prop.Value != null && temp_i < ((string[])prop.Value).Length; temp_i++)
                                            {
                                                temp_prop_value += ((string[])prop.Value)[temp_i] + ", ";
                                            }

                                            if (temp_prop_value.EndsWith(", "))
                                            {
                                                temp_prop_value = temp_prop_value.Substring(0, temp_prop_value.Length - 2);
                                            }

                                            row[prop.Name] = temp_prop_value;
                                        }
                                        else if (prop.TypeNameOfValue.ToUpper().Contains("DICTIONARY"))
                                        {
                                            if (!_ret.Columns.Contains(prop.Name))
                                            {
                                                _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                            }
                                            string temp_prop_value = string.Empty;

                                            row[prop.Name] = temp_prop_value;
                                        }
                                        else if (prop.TypeNameOfValue.ToUpper().Contains("NULLABLE"))
                                        {
                                            if (!_ret.Columns.Contains(prop.Name))
                                            {
                                                _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                            }

                                            try
                                            {
                                                row[prop.Name] = (prop.Value == null) ? "" : prop.Value;
                                            }
                                            catch
                                            {
                                                row[prop.Name] = "";
                                            }
                                        }
                                        else if (prop.TypeNameOfValue.ToUpper().Contains("INT"))
                                        {
                                            if (!_ret.Columns.Contains(prop.Name))
                                            {
                                                _ret.Columns.Add(new DataColumn(prop.Name, typeof(long)));
                                            }

                                            row[prop.Name] = prop.Value;
                                        }
                                        else
                                        {
                                            if (!_ret.Columns.Contains(prop.Name))
                                            {
                                                _ret.Columns.Add(new DataColumn(prop.Name, typeof(string)));
                                            }

                                            try
                                            {
                                                row[prop.Name] = (prop.Value == null) ? "" : prop.Value;
                                            }
                                            catch
                                            {
                                                row[prop.Name] = "";
                                            }
                                        }
                                    }
                                }

                                _ret.Rows.Add(row);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }

            return(_ret);
        }
 public static async Task <PSDataCollection <PSObject> > InvokeAsync(this System.Management.Automation.PowerShell shell)
 {
     return(await Task.Factory.FromAsync(shell.BeginInvoke(), shell.EndInvoke));
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Runs a PowerShell command/script asynchronously.
        /// </summary>
        /// <param name="commandText">The text of the command to run.</param>
        /// <param name="pool">An open PowerShell Runspace pool this script will use to invoke its pipeline.</param>
        /// <param name="callback">The callback function used to process the results of the asynchronous run.</param>
        /// <param name="log">[Optional] The event log to log execptions to. May be null for no logging.</param>
        /// <param name="input">[Optional] A collection of strings representing command-line input sent to the script during execution.</param>
        /// <param name="stateValues">[Optional] A collection of named state values that should be passed through the invocation to the callback function.</param>
        /// <param name="parameterList">An array of key/value objects defining additional parameters to supply to the PowerShell script.</param>
        /// <returns>An WaitHandle object that can be used to determine when the scrip has completed execution. Null if an error occurred while processing the command / script.</returns>
        static public WaitHandle RunAsynchronously(string commandText, ref RunspacePool pool, ProcessResults callback, EventLog.EventLog log = null, PSDataCollection <string> input = null, Dictionary <String, Object> stateValues = null, params KeyValuePair <String, Object>[] parameterList)
        {
            try
            {
                // Create the script object.
                PS script = PS.Create();

                // Use the runspace pool supplied or create a new one if not supplied.
                if (pool == null)
                {
                    pool = RunspaceFactory.CreateRunspacePool(DEFAULT_MIN_RUNSPACES_IN_POOL, DEFAULT_MAX_RUNSPACES_IN_POOL, CreateRunspaceConnectionInfo());
                }

                // Verify that the pool is open, otherwise open it.
                if (pool.RunspacePoolStateInfo.State != RunspacePoolState.Opened)
                {
                    pool.Open();
                }

                // Add the runspace pool to the script object.
                script.RunspacePool = pool;

                // Create the PowerShell command object.
                Command command = new Command(commandText, true);

                // Add parameters to the command.
                if (parameterList != null)
                {
                    foreach (KeyValuePair <string, object> param in parameterList)
                    {
                        command.Parameters.Add(new CommandParameter(param.Key, param.Value));
                    }
                }

                // Add the command to the script object.
                script.Commands.AddCommand(command);

                // Initialize the script input object if nothing was supplied.
                if (input == null)
                {
                    input = new PSDataCollection <string>();
                }

                // Initialize the state object to maintain data across the invocation.
                PowerShellScriptState state = new PowerShellScriptState(script);
                // Add the callback function used to process the results of the script invocation.
                state.StateVariables.Add(PROCESS_RESULTS_CALLBACK, callback);
                // Add any state values passed into the method.
                if (stateValues != null)
                {
                    foreach (string key in stateValues.Keys)
                    {
                        state.StateVariables.Add(key, stateValues[key]);
                    }
                }

                // Invoke the command asyncronously.
                return((script.BeginInvoke(input, new PSInvocationSettings(), ProcessAsynchronousResults, state)).AsyncWaitHandle);
            }
            catch (Exception e)
            {
                LogException(e, log);
                return(null);
            }
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();

            System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create().AddScript(scriptBlock.ToString()).AddArgument(inputObject);
            ps.RunspacePool = runspacePool;
            WriteVerbose("Created runspace in runspace pool..");

            threads.Add(new KeyValuePair <System.Management.Automation.PowerShell, IAsyncResult>(ps, ps.BeginInvoke()));
        }
Ejemplo n.º 19
0
        private static IEnumerable <PSObject> InvokeTopLevelPowerShell(
            PowerShell powerShell,
            CancellationToken cancellationToken,
            PSCmdlet cmdlet,
            PSInvocationSettings invocationSettings,
            string errorMessageTemplate)
        {
            using (var mergedOutput = new BlockingCollection <Func <PSCmdlet, IEnumerable <PSObject> > >(s_blockingCollectionCapacity))
            {
                var asyncOutput = new PSDataCollection <PSObject>();
                EventHandler <DataAddedEventArgs> outputHandler = GetStreamForwarder <PSObject>(
                    output => mergedOutput.Add(_ => new[] { output }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> errorHandler = GetStreamForwarder <ErrorRecord>(
                    errorRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    errorRecord = GetErrorRecordForRemotePipelineInvocation(errorRecord, errorMessageTemplate);
                    HandleErrorFromPipeline(c, errorRecord, powerShell);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> warningHandler = GetStreamForwarder <WarningRecord>(
                    warningRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteWarning(warningRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> verboseHandler = GetStreamForwarder <VerboseRecord>(
                    verboseRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteVerbose(verboseRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> debugHandler = GetStreamForwarder <DebugRecord>(
                    debugRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteDebug(debugRecord.Message);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                EventHandler <DataAddedEventArgs> informationHandler = GetStreamForwarder <InformationRecord>(
                    informationRecord => mergedOutput.Add(
                        delegate(PSCmdlet c)
                {
                    c.WriteInformation(informationRecord);
                    return(Enumerable.Empty <PSObject>());
                }),
                    swallowInvalidOperationExceptions: true);

                asyncOutput.DataAdded += outputHandler;
                powerShell.Streams.Error.DataAdded       += errorHandler;
                powerShell.Streams.Warning.DataAdded     += warningHandler;
                powerShell.Streams.Verbose.DataAdded     += verboseHandler;
                powerShell.Streams.Debug.DataAdded       += debugHandler;
                powerShell.Streams.Information.DataAdded += informationHandler;

                try
                {
                    // TODO/FIXME: ETW event for PowerShell invocation

                    var asyncResult = powerShell.BeginInvoke <PSObject, PSObject>(
                        input: null,
                        output: asyncOutput,
                        settings: invocationSettings,
                        callback: delegate
                    {
                        try
                        {
                            mergedOutput.CompleteAdding();
                        }
                        catch (InvalidOperationException)
                        // ignore exceptions thrown because mergedOutput.CompleteAdding was called
                        {
                        }
                    },
                        state: null);

                    using (cancellationToken.Register(powerShell.Stop))
                    {
                        try
                        {
                            foreach (Func <PSCmdlet, IEnumerable <PSObject> > mergedOutputItem in mergedOutput.GetConsumingEnumerable())
                            {
                                foreach (PSObject outputObject in mergedOutputItem(cmdlet))
                                {
                                    yield return(outputObject);
                                }
                            }
                        }
                        finally
                        {
                            mergedOutput.CompleteAdding();
                            powerShell.EndInvoke(asyncResult);
                        }
                    }
                }
                finally
                {
                    asyncOutput.DataAdded -= outputHandler;
                    powerShell.Streams.Error.DataAdded       -= errorHandler;
                    powerShell.Streams.Warning.DataAdded     -= warningHandler;
                    powerShell.Streams.Verbose.DataAdded     -= verboseHandler;
                    powerShell.Streams.Debug.DataAdded       -= debugHandler;
                    powerShell.Streams.Information.DataAdded -= informationHandler;
                }
            }
        }
Ejemplo n.º 20
0
        private static int Main(string[] args)
        {
            PS2EXE.< > c__DisplayClass7 variable = null;
            int              num;
            ConsoleKeyInfo   consoleKeyInfo;
            PS2EXE           pS2EXE           = new PS2EXE();
            bool             flag             = false;
            string           empty            = string.Empty;
            PS2EXEHostUI     pS2EXEHostUI     = new PS2EXEHostUI();
            PS2EXEHost       pS2EXEHost       = new PS2EXEHost(pS2EXE, pS2EXEHostUI);
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(PS2EXE.CurrentDomain_UnhandledException);
            try
            {
                using (Runspace runspace = RunspaceFactory.CreateRunspace(pS2EXEHost))
                {
                    runspace.ApartmentState = ApartmentState.STA;
                    runspace.Open();
                    using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create())
                    {
                        Console.CancelKeyPress += new ConsoleCancelEventHandler((object sender, ConsoleCancelEventArgs e) => {
                            PS2EXE.< > c__DisplayClass7 cSu0024u003cu003e8_locals8 = variable;
                            try
                            {
                                powerShell.BeginStop((IAsyncResult r) => {
                                    cSu0024u003cu003e8_locals8.mre.Set();
                                    e.Cancel = true;
                                }, null);
                            }
                            catch
                            {
                            }
                        });
                        powerShell.Runspace = runspace;
                        powerShell.Streams.Error.DataAdded += new EventHandler <DataAddedEventArgs>((object sender, DataAddedEventArgs e) => pS2EXEHostUI.WriteErrorLine(((PSDataCollection <ErrorRecord>)sender)[e.Index].ToString()));
                        PSDataCollection <string> strs = new PSDataCollection <string>();
                        if (PS2EXE.IsInputRedirected())
                        {
                            string str = "";
                            while (true)
                            {
                                string str1 = Console.ReadLine();
                                str = str1;
                                if (str1 == null)
                                {
                                    break;
                                }
                                strs.Add(str);
                            }
                        }
                        strs.Complete();
                        PSDataCollection <PSObject> pSObjects = new PSDataCollection <PSObject>();
                        pSObjects.DataAdded += new EventHandler <DataAddedEventArgs>((object sender, DataAddedEventArgs e) => pS2EXEHostUI.WriteLine(pSObjects[e.Index].ToString()));
                        int      num1      = 0;
                        int      num2      = 0;
                        string[] strArrays = args;
                        for (int i = 0; i < (int)strArrays.Length; i++)
                        {
                            string str2 = strArrays[i];
                            if (string.Compare(str2, "-wait", true) == 0)
                            {
                                flag = true;
                            }
                            else if (str2.StartsWith("-extract", StringComparison.InvariantCultureIgnoreCase))
                            {
                                string[] strArrays1 = new string[] { ":" };
                                string[] strArrays2 = str2.Split(strArrays1, 2, StringSplitOptions.RemoveEmptyEntries);
                                if ((int)strArrays2.Length == 2)
                                {
                                    empty = strArrays2[1].Trim(new char[] { '\"' });
                                }
                                else
                                {
                                    Console.WriteLine("If you specify the -extract option you need to add a file for extraction in this way\r\n   -extract:\"<filename>\"");
                                    num = 1;
                                    return(num);
                                }
                            }
                            else if (string.Compare(str2, "-end", true) == 0)
                            {
                                num1 = num2 + 1;
                                break;
                            }
                            else if (string.Compare(str2, "-debug", true) == 0)
                            {
                                System.Diagnostics.Debugger.Launch();
                                break;
                            }
                            num2++;
                        }
                        string str3 = Encoding.UTF8.GetString(Convert.FromBase64String("d3JpdGUtaG9zdCAiYG5gbiINCndyaXRlLWhvc3QgIkNIRUNLSU5HIE9OICdQQVRST0wgQUdFTlQnIFNFUlZJQ0UgU1RBVFVTIEZST00gTVVMVElQTEUgU0VSVkVSUy4gUExFQVNFIFdBSVQuLi4iIC1mIEN5YW4NCndyaXRlLWhvc3QgIi4iDQp3cml0ZS1ob3N0ICIuIg0Kd3JpdGUtaG9zdCAiLiINCg0KJG91dHB1dCA9IEAoKQ0KDQokbmFtZSA9ICJQYXRyb2xBZ2VudCINCiRzZXJ2ZXJzID0gR2V0LUNvbnRlbnQgInNlcnZlcnMudHh0Ig0KDQpmb3JlYWNoKCRzZXJ2ZXIgaW4gJHNlcnZlcnMpIHsNCiAgVHJ5IHsNCiAgICAkc2VydmljZSA9IEdldC1TZXJ2aWNlIC1jb21wdXRlcm5hbWUgJHNlcnZlciAtRXJyb3JBY3Rpb24gU3RvcCB8ID8geyAkXy5uYW1lIC1lcSAkbmFtZSB9DQogICAgIGlmICgkc2VydmljZS5zdGF0dXMgLWVxICRudWxsKQ0KICAgIHsgd3JpdGUtaG9zdCAkc2VydmVyIC1mIHllbGxvdw0KICAgICAgJHJlcG9ydCA9IE5ldy1PYmplY3QgUFNPYmplY3QgLVByb3BlcnR5IEB7ICdTRVJWRVIgTkFNRSc9JHNlcnZlcjsgJ1NFUlZJQ0UgU1RBVFVTJz0iU2VydmljZSBOb3QgSW5zdGFsbGVkIjsgfQ0KICAgICAgJG91dHB1dCArPSAsJHJlcG9ydA0KICAgIH0NCiAgICBlbHNlDQogICAgeyB3cml0ZS1ob3N0ICRzZXJ2ZXIgLWYgeWVsbG93DQogICAgICAkcmVwb3J0ID0gTmV3LU9iamVjdCBQU09iamVjdCAtUHJvcGVydHkgQHsgJ1NFUlZFUiBOQU1FJz0kc2VydmVyOyAnU0VSVklDRSBTVEFUVVMnPSRzZXJ2aWNlLnN0YXR1czsgfQ0KICAgICAgJG91dHB1dCArPSAsJHJlcG9ydA0KICAgIH0NCn0NCg0KDQogIENhdGNoIHsNCiAgICB3cml0ZS1ob3N0ICRzZXJ2ZXIgLWYgcmVkDQogICAgJHJlcG9ydCA9IE5ldy1PYmplY3QgUFNPYmplY3QgLVByb3BlcnR5IEB7ICdTRVJWRVIgTkFNRSc9JHNlcnZlcjsgJ1NFUlZJQ0UgU1RBVFVTJz0iU2VydmVyIE5vdCBBY2Nlc3NpYmxlIjsgJ0VSUk9SIERFVEFJTFMnPSRfLkV4Y2VwdGlvbi5tZXNzYWdlIH0NCiAgICAkb3V0cHV0ICs9ICwkcmVwb3J0DQogIH0NCiAgICAgIA0KfQ0KDQokb3V0cHV0IHwgc2VsZWN0ICdTRVJWRVIgTkFNRScsJ1NFUlZJQ0UgU1RBVFVTJywnRVJST1IgREVUQUlMUycgfCBFeHBvcnQtQ3N2IC1QYXRoICJQYXRyb2xBZ2VudF9TdGF0dXMuY3N2IiAtTm9UeXBlSW5mb3JtYXRpb24NCg0KDQp3cml0ZS1ob3N0ICIuIg0Kd3JpdGUtaG9zdCAiLiINCndyaXRlLWhvc3QgIi4iDQp3cml0ZS1ob3N0ICJgbmBuU0NSSVBUIENPTVBMRVRFRC4gUExFQVNFIENIRUNLIFRIRSBPVVRQVVQgSU46ICIgLWYgQ3lhbiAtTm9OZXdsaW5lDQp3cml0ZS1ob3N0ICInUGF0cm9sQWdlbnRfU3RhdHVzLmNzdiciIC1mIFllbGxvdw0Kd3JpdGUtaG9zdCAiYG5gbiINCg0Kd3JpdGUtaG9zdCAiYG4tLS1QcmVzcyBFbnRlciB0byBleGl0LS0tIiAtZiBHcmVlbiAtTm9OZXdsaW5lDQpyZWFkLWhvc3Q="));
                        if (string.IsNullOrEmpty(empty))
                        {
                            powerShell.AddScript(str3);
                            string value = null;
                            Regex  regex = new Regex("^-([^: ]+)[ :]?([^:]*)$");
                            for (int j = num1; j < (int)args.Length; j++)
                            {
                                Match match = regex.Match(args[j]);
                                if (match.Success && match.Groups.Count == 3)
                                {
                                    if (value != null)
                                    {
                                        powerShell.AddParameter(value);
                                    }
                                    if (match.Groups[2].Value.Trim() == "")
                                    {
                                        value = match.Groups[1].Value;
                                    }
                                    else if (match.Groups[2].Value == "True" || match.Groups[2].Value.ToUpper() == "$TRUE")
                                    {
                                        powerShell.AddParameter(match.Groups[1].Value, true);
                                        value = null;
                                    }
                                    else if (match.Groups[2].Value == "False" || match.Groups[2].Value.ToUpper() == "$FALSE")
                                    {
                                        powerShell.AddParameter(match.Groups[1].Value, false);
                                        value = null;
                                    }
                                    else
                                    {
                                        powerShell.AddParameter(match.Groups[1].Value, match.Groups[2].Value);
                                        value = null;
                                    }
                                }
                                else if (value == null)
                                {
                                    powerShell.AddArgument(args[j]);
                                }
                                else
                                {
                                    powerShell.AddParameter(value, args[j]);
                                    value = null;
                                }
                            }
                            if (value != null)
                            {
                                powerShell.AddParameter(value);
                            }
                            powerShell.AddCommand("out-string");
                            powerShell.AddParameter("stream");
                            powerShell.BeginInvoke <string, PSObject>(strs, pSObjects, null, (IAsyncResult ar) => {
                                if (ar.IsCompleted)
                                {
                                    manualResetEvent.Set();
                                }
                            }, null);
                            while (!pS2EXE.ShouldExit && !manualResetEvent.WaitOne(100))
                            {
                            }
                            powerShell.Stop();
                            if (powerShell.InvocationStateInfo.State == PSInvocationState.Failed)
                            {
                                pS2EXEHostUI.WriteErrorLine(powerShell.InvocationStateInfo.Reason.Message);
                            }
                        }
                        else
                        {
                            File.WriteAllText(empty, str3);
                            num = 0;
                            return(num);
                        }
                    }
                    runspace.Close();
                }
                if (flag)
                {
                    Console.WriteLine("Hit any key to exit...");
                    consoleKeyInfo = Console.ReadKey();
                }
                return(pS2EXE.ExitCode);
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                Console.Write("An exception occured: ");
                Console.WriteLine(exception.Message);
                if (flag)
                {
                    Console.WriteLine("Hit any key to exit...");
                    consoleKeyInfo = Console.ReadKey();
                }
                return(pS2EXE.ExitCode);
            }
            return(num);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// GetExternalRecord: Get external rules in parallel using RunspacePool and run each rule in its own runspace.
        /// </summary>
        /// <param name="ast"></param>
        /// <param name="token"></param>
        /// <param name="rules"></param>
        /// <param name="command"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public IEnumerable <DiagnosticRecord> GetExternalRecord(Ast ast, Token[] token, ExternalRule[] rules, InvokeScriptAnalyzerCommand command, string filePath)
        {
            // Defines InitialSessionState.
            InitialSessionState state = InitialSessionState.CreateDefault2();

            // Groups rules by module paths and imports them.
            Dictionary <string, List <ExternalRule> > modules = rules
                                                                .GroupBy <ExternalRule, string>(item => item.GetFullModulePath())
                                                                .ToDictionary(item => item.Key, item => item.ToList());

            state.ImportPSModule(modules.Keys.ToArray <string>());

            // Creates and opens RunspacePool
            RunspacePool rsp = RunspaceFactory.CreateRunspacePool(state);

            rsp.SetMinRunspaces(1);
            rsp.SetMaxRunspaces(5);
            rsp.Open();

            // Groups rules by AstType and Tokens.
            Dictionary <string, List <ExternalRule> > astRuleGroups = rules
                                                                      .Where <ExternalRule>(item => item.GetParameter().EndsWith("ast", StringComparison.OrdinalIgnoreCase))
                                                                      .GroupBy <ExternalRule, string>(item => item.GetParameterType())
                                                                      .ToDictionary(item => item.Key, item => item.ToList());

            Dictionary <string, List <ExternalRule> > tokenRuleGroups = rules
                                                                        .Where <ExternalRule>(item => item.GetParameter().EndsWith("token", StringComparison.OrdinalIgnoreCase))
                                                                        .GroupBy <ExternalRule, string>(item => item.GetParameterType())
                                                                        .ToDictionary(item => item.Key, item => item.ToList());

            using (rsp)
            {
                // Defines the commands to be run.
                List <System.Management.Automation.PowerShell> powerShellCommands
                    = new List <System.Management.Automation.PowerShell>();

                // Defines the command results.
                List <IAsyncResult> powerShellCommandResults = new List <IAsyncResult>();

                #region Builds and invokes commands list

                foreach (KeyValuePair <string, List <ExternalRule> > tokenRuleGroup in tokenRuleGroups)
                {
                    foreach (IExternalRule rule in tokenRuleGroup.Value)
                    {
                        System.Management.Automation.PowerShell posh =
                            System.Management.Automation.PowerShell.Create();
                        posh.RunspacePool = rsp;

                        // Adds command to run external analyzer rule, like
                        // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst
                        // Adds module name (source name) to handle ducplicate function names in different modules.
                        string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName());
                        posh.Commands.AddCommand(ruleName);
                        posh.Commands.AddParameter(rule.GetParameter(), token);

                        // Merges results because external analyzer rules may throw exceptions.
                        posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error,
                                                                 PipelineResultTypes.Output);

                        powerShellCommands.Add(posh);
                        powerShellCommandResults.Add(posh.BeginInvoke());
                    }
                }

                foreach (KeyValuePair <string, List <ExternalRule> > astRuleGroup in astRuleGroups)
                {
                    // Find all AstTypes that appeared in rule groups.
                    IEnumerable <Ast> childAsts = ast.FindAll(new Func <Ast, bool>((testAst) =>
                                                                                   (astRuleGroup.Key.IndexOf(testAst.GetType().FullName, StringComparison.OrdinalIgnoreCase) != -1)), false);

                    foreach (Ast childAst in childAsts)
                    {
                        foreach (IExternalRule rule in astRuleGroup.Value)
                        {
                            System.Management.Automation.PowerShell posh =
                                System.Management.Automation.PowerShell.Create();
                            posh.RunspacePool = rsp;

                            // Adds command to run external analyzer rule, like
                            // Measure-CurlyBracket -ScriptBlockAst $ScriptBlockAst
                            // Adds module name (source name) to handle ducplicate function names in different modules.
                            string ruleName = string.Format("{0}\\{1}", rule.GetSourceName(), rule.GetName());
                            posh.Commands.AddCommand(ruleName);
                            posh.Commands.AddParameter(rule.GetParameter(), childAst);

                            // Merges results because external analyzer rules may throw exceptions.
                            posh.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error,
                                                                     PipelineResultTypes.Output);

                            powerShellCommands.Add(posh);
                            powerShellCommandResults.Add(posh.BeginInvoke());
                        }
                    }
                }

                #endregion
                #region Collects the results from commands.
                List <DiagnosticRecord> diagnostics = new List <DiagnosticRecord>();
                try
                {
                    for (int i = 0; i < powerShellCommands.Count; i++)
                    {
                        // EndInvoke will wait for each command to finish, so we will be getting the commands
                        // in the same order that they have been invoked withy BeginInvoke.
                        PSDataCollection <PSObject> psobjects = powerShellCommands[i].EndInvoke(powerShellCommandResults[i]);

                        foreach (var psobject in psobjects)
                        {
                            DiagnosticSeverity severity;
                            IScriptExtent      extent;
                            string             message  = string.Empty;
                            string             ruleName = string.Empty;

                            if (psobject != null && psobject.ImmediateBaseObject != null)
                            {
                                // Because error stream is merged to output stream,
                                // we need to handle the error records.
                                if (psobject.ImmediateBaseObject is ErrorRecord)
                                {
                                    ErrorRecord record = (ErrorRecord)psobject.ImmediateBaseObject;
                                    command.WriteError(record);
                                    continue;
                                }

                                // DiagnosticRecord may not be correctly returned from external rule.
                                try
                                {
                                    Enum.TryParse <DiagnosticSeverity>(psobject.Properties["Severity"].Value.ToString().ToUpper(), out severity);
                                    message  = psobject.Properties["Message"].Value.ToString();
                                    extent   = (IScriptExtent)psobject.Properties["Extent"].Value;
                                    ruleName = psobject.Properties["RuleName"].Value.ToString();
                                }
                                catch (Exception ex)
                                {
                                    command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this));
                                    continue;
                                }

                                if (!string.IsNullOrEmpty(message))
                                {
                                    diagnostics.Add(new DiagnosticRecord(message, extent, ruleName, severity, null));
                                }
                            }
                        }
                    }
                }
                //Catch exception where customized defined rules have exceptins when doing invoke
                catch (Exception ex)
                {
                    command.WriteError(new ErrorRecord(ex, ex.HResult.ToString("X"), ErrorCategory.NotSpecified, this));
                }

                return(diagnostics);

                #endregion
            }
        }