private void HandleException(Exception e, int taskId, TaskHost host)
        {
            if (e is AggregateException aggregate)
            {
                foreach (var inner in aggregate.InnerExceptions)
                {
                    HandleException(inner, taskId, host);
                }
            }
            else if (e.InnerException is Exception inner)
            {
                HandleException(inner, taskId, host);
            }
            else
            {
                _exceptions.Add(e);

                host.UI.WriteErrorLine(GetMostHelpfulMessage(e));

                var data = e.Data;
                if (data != null)
                {
                    data["TaskId"] = taskId;
                }
            }
        }
Exemple #2
0
            public TestHarness(int taskId = 42)
            {
                MockHost = Mocks.Create <PSHost>();
                MockUI   = Mocks.Create <PSHostUserInterface>(MockBehavior.Loose);

                MockHost
                .SetupGet(h => h.UI)
                .Returns(MockUI.Object);

                TaskHost = new TaskHost(MockHost.Object, new ConsoleState(), taskId);
            }
        private void TaskMain(int taskId, TaskWork work)
        {
            var host = new TaskHost(Host, _console, taskId);

            try
            {
                host.UI.WriteLine("Starting");
                RunScript(taskId, work, host);
            }
            catch (Exception e)
            {
                _cancellation.Cancel();
                HandleException(e, taskId, host);
            }
            finally
            {
                host.UI.WriteLine("Ended");
            }
        }
        private void RunScript(int taskId, TaskWork work, TaskHost host)
        {
            var state = CreateInitialSessionState(taskId, work);

            using (var runspace = RunspaceFactory.CreateRunspace(host, state))
            {
                runspace.Name          = $"Invoke-Concurrent-{taskId}";
                runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
                runspace.Open();

                using (var shell = PowerShell.Create())
                {
                    var output = new PSDataCollection <PSObject>();
                    output.DataAdding += (s, e) => HandleOutput(taskId, e.ItemAdded);

                    shell.Runspace = runspace;
                    shell.AddScript(work.Script.ToString()).Invoke(null, output);
                }

                runspace.Close();
            }
        }