Ejemplo n.º 1
0
        internal static PSDataCollection <object> Serialize(IEnumerable collection)
        {
            PSDataCollection <object> psdataCollection = new PSDataCollection <object>();

            if (collection != null)
            {
                foreach (object obj in collection)
                {
                    if (MonadCommand.CanSerialize(obj))
                    {
                        psdataCollection.Add(MonadCommand.Serialize(obj));
                    }
                    else if (obj is Enum)
                    {
                        psdataCollection.Add(obj.ToString());
                    }
                    else
                    {
                        psdataCollection.Add(obj);
                    }
                }
            }
            psdataCollection.Complete();
            return(psdataCollection);
        }
Ejemplo n.º 2
0
        public void ProcessData_WhenSenderIsPSDataCollection_RemovesItemFromCollection()
        {
            var sender   = new PSDataCollection <string>();
            var expected = "string0";

            sender.Add(expected);
            sender.Add("string1");

            PwshRunner.ProcessData <string>(sender, 0, o => { });

            Assert.Single(sender);
            Assert.DoesNotContain(sender, o => expected.Equals(o));
        }
Ejemplo n.º 3
0
 private void ValidateAndThrowRunspaceOpenModuleLoadException(PowerShell pse, List <ErrorRecord> errors, bool startLifeCycleEventWritten, string moduleName, RunspaceOpenModuleLoadException exception)
 {
     if (this.InitialSessionState.ThrowOnRunspaceOpenError)
     {
         RunspaceOpenModuleLoadException exception2 = null;
         if (exception != null)
         {
             exception2 = exception;
         }
         else if ((pse.Streams.Error.Count > 0) || (errors.Count > 0))
         {
             ErrorRecord record;
             Exception   exception3;
             PSDataCollection <ErrorRecord> datas = new PSDataCollection <ErrorRecord>();
             if (errors.Count > 0)
             {
                 record     = errors[0];
                 exception3 = record.Exception;
                 foreach (ErrorRecord record2 in errors)
                 {
                     datas.Add(record2);
                 }
             }
             else
             {
                 record     = pse.Streams.Error[0];
                 exception3 = record.Exception;
                 foreach (ErrorRecord record3 in pse.Streams.Error)
                 {
                     datas.Add(record3);
                 }
             }
             runspaceInitTracer.WriteLine("Runspace open failed while loading module '{0}': First error {1}", new object[] { moduleName, exception3 });
             exception2 = new RunspaceOpenModuleLoadException(moduleName, datas);
         }
         if (exception2 != null)
         {
             this.LogEngineHealthEvent(exception2);
             if (startLifeCycleEventWritten)
             {
                 MshLog.LogEngineLifecycleEvent(this._engine.Context, EngineState.Stopped);
             }
             base.SetRunspaceState(RunspaceState.Broken, exception2);
             base.RaiseRunspaceStateEvents();
             throw exception2;
         }
     }
 }
Ejemplo n.º 4
0
        public static string ExtractErrorFromErrorRecord(this Runspace runspace, ErrorRecord record)
        {
            Pipeline pipeline = runspace.CreatePipeline("$input", false);
            pipeline.Commands.Add("out-string");

            Collection<PSObject> result;
            using (PSDataCollection<object> inputCollection = new PSDataCollection<object>())
            {
                inputCollection.Add(record);
                inputCollection.Complete();
                result = pipeline.Invoke(inputCollection);
            }

            if (result.Count > 0)
            {
                string str = result[0].BaseObject as string;
                if (!string.IsNullOrEmpty(str))
                {
                    // Remove \r\n, which is added by the Out-String cmdlet.
                    return str.Substring(0, str.Length - 2);
                }
            }

            return String.Empty;
        }
Ejemplo n.º 5
0
        public async void RunScript_ReadsDataFromInputStream()
        {
            var lf       = TestLoggerFactory.Create();
            var script   = @"$Input | ForEach { Write-Output $_ }";
            var expected = new[] { 32, 120, 71, 89, 20 };

            var input = new PSDataCollection <PSObject>(5);

            _ = Task.Run(
                () =>
            {
                foreach (var num in expected)
                {
                    input.Add(num);
                    Thread.Sleep(num);
                }

                input.Complete();
            }
                );

            var result = await PwshRunner.RunScript(script, lf.CreateLogger("Test"), null, input);

            var actual = result.Select(o => (int)o.BaseObject).ToArray();

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Processes records from the input pipeline.
 /// For each input object, the command encrypts
 /// and exports the object.
 /// </summary>
 protected override void ProcessRecord()
 {
     if (string.Equals("ByContent", this.ParameterSetName, StringComparison.OrdinalIgnoreCase))
     {
         _inputObjects.Add(Content);
     }
 }
Ejemplo n.º 7
0
        public string ExtractErrorFromErrorRecord(ErrorRecord record)
        {
            Pipeline pipeline = _runspace.CreatePipeline(command: "$input", addToHistory: false);

            pipeline.Commands.Add("out-string");

            Collection <PSObject> result;

            using (var inputCollection = new PSDataCollection <object>())
            {
                inputCollection.Add(record);
                inputCollection.Complete();
                result = InvokeCore(pipeline, inputCollection);
            }

            if (result.Count > 0)
            {
                string str = result[0].BaseObject as string;
                if (!string.IsNullOrEmpty(str))
                {
                    // Remove \r\n, which is added by the Out-String cmdlet.
                    return(str.TrimEnd(new[] { '\r', '\n' }));
                }
            }

            return(String.Empty);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// InjectInput
 /// </summary>
 /// <param name="psObject"></param>
 public void InjectInput(PSObject psObject)
 {
     if (psObject != null)
     {
         _input.Add(psObject);
     }
 }
Ejemplo n.º 9
0
        public static string ExtractErrorFromErrorRecord(this Runspace runspace, ErrorRecord record)
        {
            Pipeline pipeline = runspace.CreatePipeline("$input", false);

            pipeline.Commands.Add("out-string");

            Collection <PSObject> result;

            using (PSDataCollection <object> inputCollection = new PSDataCollection <object>()) {
                inputCollection.Add(record);
                inputCollection.Complete();
                result = pipeline.Invoke(inputCollection);
            }

            if (result.Count > 0)
            {
                string str = result[0].BaseObject as string;
                if (!string.IsNullOrEmpty(str))
                {
                    // Remove \r\n, which is added by the Out-String cmdlet.
                    return(str.Substring(0, str.Length - 2));
                }
            }

            return(String.Empty);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Starts the pipeline script async.
        /// </summary>
        public void BeginInvoke(Queue<PSObject> queue, int count)
        {
            var input = new PSDataCollection<PSObject>(count);
            while (--count >= 0)
                input.Add(queue.Dequeue());
            input.Complete();

            _async = _posh.BeginInvoke(input);
        }
Ejemplo n.º 11
0
        /// <inheritdoc />
        protected override async Task <Result <Array <Entity>, IError> > Run(
            IStateMonad stateMonad,
            CancellationToken cancellationToken)
        {
            var script = await Script.Run(stateMonad, cancellationToken).Map(x => x.GetStringAsync());

            if (script.IsFailure)
            {
                return(script.ConvertFailure <Array <Entity> >());
            }

            Entity?vars = null;

            if (Variables != null)
            {
                var variables = await Variables.Run(stateMonad, cancellationToken);

                if (variables.IsFailure)
                {
                    return(variables.ConvertFailure <Array <Entity> >());
                }

                vars = variables.Value;
            }

            PSDataCollection <PSObject>?input = null;

        #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
            async ValueTask <Result <Unit, IError> > AddObject(Entity x, CancellationToken ct)
            {
                input.Add(PwshRunner.PSObjectFromEntity(x));
                return(Unit.Default);
            }

        #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

            if (Input != null)
            {
                var inputStream = await Input.Run(stateMonad, cancellationToken);

                if (inputStream.IsFailure)
                {
                    return(inputStream.ConvertFailure <Array <Entity> >());
                }

                input = new PSDataCollection <PSObject>();

                _ = inputStream.Value.ForEach(AddObject, cancellationToken)
                    .ContinueWith(_ => input.Complete(), cancellationToken);
            }

            var stream = PwshRunner.GetEntityEnumerable(script.Value, stateMonad.Logger, vars, input)
                         .ToSCLArray();

            return(stream);
        }
        /// <summary>
        /// To display an exception using the display formatter,
        /// run a second pipeline passing in the error record.
        /// The runtime will bind this to the $input variable,
        /// which is why $input is being piped to the Out-String
        /// cmdlet. The WriteErrorLine method is called to make sure
        /// the error gets displayed in the correct error color.
        /// </summary>
        /// <param name="e">The exception to display.</param>
        private void ReportException(Exception e)
        {
            if (e != null)
            {
                object error;
                IContainsErrorRecord icer = e as IContainsErrorRecord;
                if (icer != null)
                {
                    error = icer.ErrorRecord;
                }
                else
                {
                    error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
                }

                lock (this.instanceLock)
                {
                    this.currentPowerShell = PowerShell.Create();
                }

                this.currentPowerShell.Runspace = this.myRunSpace;

                try
                {
                    this.currentPowerShell.AddScript("$input").AddCommand("out-string");

                    // Do not merge errors, this function will swallow errors.
                    Collection <PSObject>     result;
                    PSDataCollection <object> inputCollection = new PSDataCollection <object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = this.currentPowerShell.Invoke(inputCollection);

                    if (result.Count > 0)
                    {
                        string str = result[0].BaseObject as string;
                        if (!string.IsNullOrEmpty(str))
                        {
                            // Remove \r\n, which is added by the Out-String cmdlet.
                            this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
                finally
                {
                    // Dispose of the pipeline and set it to null, locking it  because
                    // currentPowerShell may be accessed by the ctrl-C handler.
                    lock (this.instanceLock)
                    {
                        this.currentPowerShell.Dispose();
                        this.currentPowerShell = null;
                    }
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Starts the pipeline script async.
        /// </summary>
        public void BeginInvoke(Queue <PSObject> queue, int count)
        {
            var input = new PSDataCollection <PSObject>(count);

            while (--count >= 0)
            {
                input.Add(queue.Dequeue());
            }
            input.Complete();

            _async = _posh.BeginInvoke(input);
        }
Ejemplo n.º 14
0
        public void ProcessData_WhenSenderIsPSDataCollection_InvokesAction()
        {
            var sender = new PSDataCollection <object>();
            var str    = "";
            var mock   = new Mock <Action <object> >();

            sender.Add(str);

            PwshRunner.ProcessData <object>(sender, 0, mock.Object);

            mock.Verify(m => m.Invoke(str));
        }
Ejemplo n.º 15
0
        void Debug_DataAdded(object sender, DataAddedEventArgs e)
        {
            PSDataCollection <DebugRecord> collection = sender as PSDataCollection <DebugRecord>;

            lastDebug = collection[e.Index];
            PSObject       psObj    = new PSObject(lastDebug);
            PSPropertyInfo propInfo = new PSNoteProperty("TimeStamp", DateTime.Now);

            psObj.Properties.Add(new PSNoteProperty("Stream", "Debug"));
            psObj.Properties.Add(propInfo);
            timeStampedOutput.Add(psObj);

            if (Dispatcher != null)
            {
                RunOnUIThread(
                    new DispatcherOperationCallback(
                        delegate
                {
                    NotifyDebugChanged();
                    return(null);
                }),
                    true);
            }
            else
            {
                NotifyDebugChanged();
            }
        }
        private void ReportException(Exception e)
        {
            if (e != null)
            {
                object error;
                IContainsErrorRecord icer = e as IContainsErrorRecord;
                if (icer != null)
                {
                    error = icer.ErrorRecord;
                }
                else
                {
                    error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
                }

                lock (this.instanceLock)
                {
                    this.currentPowerShell = PowerShell.Create();
                }

                this.currentPowerShell.Runspace = this.myRunSpace;

                try
                {
                    this.currentPowerShell.AddScript("$input").AddCommand("out-string");

                    Collection <PSObject>     result;
                    PSDataCollection <object> inputCollection = new PSDataCollection <object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = this.currentPowerShell.Invoke(inputCollection);

                    if (result.Count > 0)
                    {
                        string str = result[0].BaseObject as string;
                        if (!string.IsNullOrEmpty(str))
                        {
                            this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
                finally
                {
                    lock (this.instanceLock)
                    {
                        this.currentPowerShell.Dispose();
                        this.currentPowerShell = null;
                    }
                }
            }
        }
Ejemplo n.º 17
0
        void CallPasswordScript(PasswordOperation Action, CSEntry csentry, SecureString oldPassword, SecureString newPassword, PasswordOptions options)
        {
            Tracer.Enter("callpasswordscript");
            PSDataCollection <PSObject> passwordPipeline = new PSDataCollection <PSObject>();

            try
            {
                Command cmd = new Command(Path.GetFullPath(PasswordManagementScript));
                cmd.Parameters.Add(new CommandParameter("Username", Username));
                cmd.Parameters.Add(new CommandParameter("Password", Password));
                cmd.Parameters.Add(new CommandParameter("Credentials", GetSecureCredentials(Username, SecureStringPassword)));

                cmd.Parameters.Add(new CommandParameter("AuxUsernameAux", UsernameAux));
                cmd.Parameters.Add(new CommandParameter("AuxPasswordAux", PasswordAux));
                cmd.Parameters.Add(new CommandParameter("AuxCredentialsAux", GetSecureCredentials(UsernameAux, SecureStringPasswordAux)));

                cmd.Parameters.Add(new CommandParameter("ConfigurationParameter", ConfigurationParameter));

                cmd.Parameters.Add(new CommandParameter("Action", Action.ToString()));

                if (options.HasFlag(PasswordOptions.UnlockAccount))
                {
                    cmd.Parameters.Add(new CommandParameter("UnlockAccount"));
                }
                if (options.HasFlag(PasswordOptions.ForceChangeAtLogOn))
                {
                    cmd.Parameters.Add(new CommandParameter("ForceChangeAtLogOn"));
                }
                if (options.HasFlag(PasswordOptions.ValidatePassword))
                {
                    cmd.Parameters.Add(new CommandParameter("ValidatePassword"));
                }
                cmd.Parameters.Add(new CommandParameter("NewPassword", newPassword.ConvertToUnsecureString()));
                if (Action == PasswordOperation.Change)
                {
                    cmd.Parameters.Add(new CommandParameter("OldPassword", oldPassword.ConvertToUnsecureString()));
                }
                passwordPipeline.Add(new PSObject(csentry));
                passwordResults = InvokePowerShellScript(cmd, passwordPipeline);
            }
            catch (Exception ex)
            {
                Tracer.TraceError("callpasswordscript", ex);
                throw;
            }
            finally
            {
                passwordPipeline = null;
                Tracer.TraceInformation("callpasswordscript");
            }
        }
Ejemplo n.º 18
0
 private void HandleResultsDataAdding(object sender, DataAddingEventArgs dataAddingArgs)
 {
     if (_debugCollection.IsOpen)
     {
         PSStreamObject streamObject = dataAddingArgs.ItemAdded as PSStreamObject;
         if (streamObject != null)
         {
             try
             {
                 _debugCollection.Add(streamObject);
             }
             catch (PSInvalidOperationException) { }
         }
     }
 }
Ejemplo n.º 19
0
        private PSDataCollection <T> CopyResults <T>(ICollection <T> fromResults)
        {
            if (fromResults != null && fromResults.Count > 0)
            {
                PSDataCollection <T> returnResults = new PSDataCollection <T>();
                foreach (var item in fromResults)
                {
                    returnResults.Add(item);
                }

                return(returnResults);
            }

            return(null);
        }
Ejemplo n.º 20
0
 private PSDataCollection <T> CopyResults <T>(ICollection <T> fromResults)
 {
     if (fromResults == null || fromResults.Count <= 0)
     {
         return(null);
     }
     else
     {
         PSDataCollection <T> ts = new PSDataCollection <T>();
         foreach (T fromResult in fromResults)
         {
             ts.Add(fromResult);
         }
         return(ts);
     }
 }
Ejemplo n.º 21
0
        private void AddToDebugBlockingCollection(PSStreamObject streamItem)
        {
            if (!_debugBlockingCollection.IsOpen)
            {
                return;
            }

            if (streamItem != null)
            {
                try
                {
                    _debugBlockingCollection.Add(streamItem);
                }
                catch (PSInvalidOperationException) { }
            }
        }
Ejemplo n.º 22
0
        private void OnData(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action != NotifyCollectionChangedAction.Add)
            {
                return;
            }

            PSDataCollection <object> input = new PSDataCollection <object>();

            foreach (var ci in e.NewItems)
            {
                input.Add(ci);
            }

            Interlocked.Exchange(ref _currentInput, input);
            RaiseTrigger();
        }
        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.º 24
0
        private void ReportException(Exception e)
        {
            object error;

            if (e is IContainsErrorRecord)
            {
                error = (e as IContainsErrorRecord).ErrorRecord;
            }
            else
            {
                error = new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
            }

            try
            {
                using (var ps = _host.CreatePowerShell())
                {
                    ps.AddScript("$input").AddCommand("Out-String");

                    // Do not merge errors, this function will swallow errors.
                    Collection <PSObject>     result;
                    PSDataCollection <object> inputCollection = new PSDataCollection <object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = ps.Invoke(inputCollection);

                    if (result.Any())
                    {
                        var str = result.First().BaseObject as string;
                        if (!string.IsNullOrEmpty(str))
                        {
                            _host.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
            }
            catch (Exception ex) // exception reporting might fail, depends on runspace state - just ignore any exception
            {
                logger.Error(ex);
            }
        }
Ejemplo n.º 25
0
        private void HandlePowerShellPStreamItem(PSStreamObject streamItem)
        {
            if (!_debugger.InBreakpoint)
            {
                // First write any accumulated items.
                foreach (var item in _debugAccumulateCollection.ReadAll())
                {
                    AddToDebugBlockingCollection(item);
                }

                // Handle new item.
                if ((_debugBlockingCollection != null) && (_debugBlockingCollection.IsOpen))
                {
                    AddToDebugBlockingCollection(streamItem);
                }
            }
            else if (_debugAccumulateCollection.IsOpen)
            {
                // Add to accumulator if debugger is stopped in breakpoint.
                _debugAccumulateCollection.Add(streamItem);
            }
        }
Ejemplo n.º 26
0
        private void HookupHostDataDelegates(ThreadJobHost host)
        {
            ThreadJobHostUI hostUI = host.UI as ThreadJobHostUI;

            System.Diagnostics.Debug.Assert(hostUI != null, "Host UI cannot be null.");

            hostUI.Output.DataAdded += (sender, dataAddedEventArgs) =>
            {
                Collection <PSObject> output = hostUI.Output.ReadAll();
                foreach (var item in output)
                {
                    _output.Add(item);
                }
            };

            hostUI.Error.DataAdded += (sender, dataAddedEventArgs) =>
            {
                Collection <ErrorRecord> error = hostUI.Error.ReadAll();
                foreach (var item in error)
                {
                    Error.Add(item);
                }
            };
        }
Ejemplo n.º 27
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.º 28
0
        protected virtual DebuggerCommandResults HandlePromptCommand(PSDataCollection<PSObject> output)
        {
            // Nested debugged runspace prompt should look like:
            // [ComputerName]: [DBG]: [Process:<id>]: [RunspaceName]: PS C:\>
            string computerName = (_runspace.ConnectionInfo != null) ? _runspace.ConnectionInfo.ComputerName : null;
            string processPartPattern = "{0}[{1}:{2}]:{3}";
            string processPart = StringUtil.Format(processPartPattern,
                @"""",
                DebuggerStrings.NestedRunspaceDebuggerPromptProcessName,
                @"$($PID)",
                @"""");
            string locationPart = @"""PS $($executionContext.SessionState.Path.CurrentLocation)> """;
            string promptScript = "'[DBG]: '" + " + " + processPart + " + " + "' [" + CodeGeneration.EscapeSingleQuotedStringContent(_runspace.Name) + "]: '" + " + " + locationPart;

            // Get the command prompt from the wrapped debugger.
            PSCommand promptCommand = new PSCommand();
            promptCommand.AddScript(promptScript);
            PSDataCollection<PSObject> promptOutput = new PSDataCollection<PSObject>();
            _wrappedDebugger.ProcessCommand(promptCommand, promptOutput);
            string promptString = (promptOutput.Count == 1) ? promptOutput[0].BaseObject as string : string.Empty;
            var nestedPromptString = new System.Text.StringBuilder();

            // For remote runspaces display computer name in prompt.
            if (!string.IsNullOrEmpty(computerName))
            {
                nestedPromptString.Append("[" + computerName + "]:");
            }

            nestedPromptString.Append(promptString);

            // Fix up for non-remote runspaces since the runspace is not in a nested prompt
            // but the root runspace is.
            if (string.IsNullOrEmpty(computerName))
            {
                nestedPromptString.Insert(nestedPromptString.Length - 1, ">");
            }

            output.Add(nestedPromptString.ToString());

            return new DebuggerCommandResults(null, true);
        }
Ejemplo n.º 29
0
        protected override DebuggerCommandResults HandleCallStack(PSDataCollection<PSObject> output)
        {
            // First get call stack from wrapped debugger
            PSCommand cmd = new PSCommand();
            cmd.AddCommand("Get-PSCallStack");
            PSDataCollection<PSObject> callStackOutput = new PSDataCollection<PSObject>();
            _wrappedDebugger.ProcessCommand(cmd, callStackOutput);

            // Next get call stack from parent debugger.
            PSDataCollection<CallStackFrame> callStack = _rootDebugger.GetCallStack().ToArray();

            // Combine call stack info.
            foreach (var item in callStack)
            {
                callStackOutput.Add(new PSObject(item));
            }

            // Display call stack info as formatted.
            using (PowerShell ps = PowerShell.Create())
            {
                ps.AddCommand("Out-String").AddParameter("Stream", true);
                ps.Invoke(callStackOutput, output);
            }

            return new DebuggerCommandResults(null, true);
        }
Ejemplo n.º 30
0
		private static void PowerShellInvocation_ErrorAdding(object sender, DataAddingEventArgs e, HostSettingCommandMetadata commandMetadata, PSDataCollection<PSObject> output)
		{
			ErrorRecord itemAdded = e.ItemAdded as ErrorRecord;
			if (itemAdded != null)
			{
				if (commandMetadata != null)
				{
					ScriptPosition scriptPosition = new ScriptPosition(commandMetadata.CommandName, commandMetadata.StartLineNumber, commandMetadata.StartColumnNumber, null);
					ScriptPosition scriptPosition1 = new ScriptPosition(commandMetadata.CommandName, commandMetadata.EndLineNumber, commandMetadata.EndColumnNumber, null);
					ScriptExtent scriptExtent = new ScriptExtent(scriptPosition, scriptPosition1);
					if (itemAdded.InvocationInfo != null)
					{
						itemAdded.InvocationInfo.DisplayScriptPosition = scriptExtent;
					}
				}
				if (output != null)
				{
					output.Add(PSObject.AsPSObject(itemAdded));
				}
			}
		}
Ejemplo n.º 31
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="command"></param>
        /// <param name="sb"></param>
        /// <param name="filePath"></param>
        /// <param name="initSb"></param>
        /// <param name="argumentList"></param>
        /// <param name="inputObject"></param>
        /// <param name="psCmdlet"></param>
        /// <param name="currentLocationPath"></param>
        /// <param name="streamingHost"></param>
        public ThreadJob(
            string name,
            string command,
            ScriptBlock sb,
            string filePath,
            ScriptBlock initSb,
            object[] argumentList,
            PSObject inputObject,
            PSCmdlet psCmdlet,
            string currentLocationPath,
            PSHost streamingHost)
            : base(command, name)
        {
            _sb           = sb;
            _filePath     = filePath;
            _initSb       = initSb;
            _argumentList = argumentList;
            _input        = new PSDataCollection <object>();
            if (inputObject != null)
            {
                _input.Add(inputObject);
            }
            _output              = new PSDataCollection <PSObject>();
            _streamingHost       = streamingHost;
            _currentLocationPath = currentLocationPath;

            this.PSJobTypeName = "ThreadJob";

            // Get script block to run.
            if (!string.IsNullOrEmpty(_filePath))
            {
                _sb = GetScriptBlockFromFile(_filePath, psCmdlet);
                if (_sb == null)
                {
                    throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile);
                }
            }
            else if (_sb == null)
            {
                throw new PSArgumentNullException(Properties.Resources.NoScriptToRun);
            }

            // Create Runspace/PowerShell object and state callback.
            // The job script/command will run in a separate thread associated with the Runspace.
            var iss = InitialSessionState.CreateDefault2();

            // Determine session language mode for Windows platforms
            WarningRecord lockdownWarning = null;

            if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase))
            {
                bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce);
                if (enforceLockdown && !string.IsNullOrEmpty(_filePath))
                {
                    // If script source is a file, check to see if it is trusted by the lock down policy
                    enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce);

                    if (!enforceLockdown && (_initSb != null))
                    {
                        // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce
                        // lock down.  Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script.
                        enforceLockdown = true;
                        lockdownWarning = new WarningRecord(
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Properties.Resources.CannotRunTrustedFileInFL,
                                _filePath));
                    }
                }

                iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage;
            }

            if (_streamingHost != null)
            {
                _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss);
            }
            else
            {
                _rs = RunspaceFactory.CreateRunspace(iss);
            }
            _ps          = PowerShell.Create();
            _ps.Runspace = _rs;
            _ps.InvocationStateChanged += (sender, psStateChanged) =>
            {
                var newStateInfo = psStateChanged.InvocationStateInfo;

                // Update Job state.
                switch (newStateInfo.State)
                {
                case PSInvocationState.Running:
                    SetJobState(JobState.Running);
                    break;

                case PSInvocationState.Stopped:
                    SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Failed:
                    SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Completed:
                    if (_runningInitScript)
                    {
                        // Begin running main script.
                        _runningInitScript = false;
                        RunScript();
                    }
                    else
                    {
                        SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true);
                    }
                    break;
                }
            };

            // Get any using variables.
            var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>();

            if (usingAsts != null &&
                usingAsts.FirstOrDefault() != null)
            {
                // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater
                _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet);
            }

            // Hook up data streams.
            this.Output = _output;
            this.Output.EnumeratorNeverBlocks = true;

            this.Error = _ps.Streams.Error;
            this.Error.EnumeratorNeverBlocks = true;

            this.Progress = _ps.Streams.Progress;
            this.Progress.EnumeratorNeverBlocks = true;

            this.Verbose = _ps.Streams.Verbose;
            this.Verbose.EnumeratorNeverBlocks = true;

            this.Warning = _ps.Streams.Warning;
            this.Warning.EnumeratorNeverBlocks = true;
            if (lockdownWarning != null)
            {
                this.Warning.Add(lockdownWarning);
            }

            this.Debug = _ps.Streams.Debug;
            this.Debug.EnumeratorNeverBlocks = true;

            this.Information = _ps.Streams.Information;
            this.Information.EnumeratorNeverBlocks = true;

            // Create the JobManager job definition and job specification, and add to the JobManager.
            ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name);
            Dictionary <string, object> parameterCollection = new Dictionary <string, object>();

            parameterCollection.Add("NewJob", this);
            var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection);
            var newJob           = psCmdlet.JobManager.NewJob(jobSpecification);

            System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job");
        }
Ejemplo n.º 32
0
        public string ExtractErrorFromErrorRecord(ErrorRecord record)
        {
            Pipeline pipeline = _runspace.CreatePipeline(command: "$input", addToHistory: false);
            pipeline.Commands.Add("out-string");

            Collection<PSObject> result;
            using (var inputCollection = new PSDataCollection<object>())
            {
                inputCollection.Add(record);
                inputCollection.Complete();
                result = InvokeCore(pipeline, inputCollection);
            }

            if (result.Count > 0)
            {
                string str = result[0].BaseObject as string;
                if (!string.IsNullOrEmpty(str))
                {
                    // Remove \r\n, which is added by the Out-String cmdlet.
                    return str.TrimEnd(new[] { '\r', '\n' });
                }
            }

            return String.Empty;
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="command"></param>
        /// <param name="sb"></param>
        /// <param name="filePath"></param>
        /// <param name="initSb"></param>
        /// <param name="argumentList"></param>
        /// <param name="inputObject"></param>
        /// <param name="psCmdlet"></param>
        public ThreadJob(
            string name,
            string command,
            ScriptBlock sb,
            string filePath,
            ScriptBlock initSb,
            object[] argumentList,
            PSObject inputObject,
            PSCmdlet psCmdlet)
            : base(command, name)
        {
            _sb           = sb;
            _filePath     = filePath;
            _initSb       = initSb;
            _argumentList = argumentList;
            _input        = new PSDataCollection <object>();
            if (inputObject != null)
            {
                _input.Add(inputObject);
            }
            _output = new PSDataCollection <PSObject>();

            this.PSJobTypeName = "ThreadJob";

            // Create host object for thread jobs.
            ThreadJobHost host = new ThreadJobHost();

            HookupHostDataDelegates(host);

            // Create Runspace/PowerShell object and state callback.
            // The job script/command will run in a separate thread associated with the Runspace.
            _rs          = RunspaceFactory.CreateRunspace(host);
            _ps          = PowerShell.Create();
            _ps.Runspace = _rs;
            _ps.InvocationStateChanged += (sender, psStateChanged) =>
            {
                var newStateInfo = psStateChanged.InvocationStateInfo;

                // Update Job state.
                switch (newStateInfo.State)
                {
                case PSInvocationState.Running:
                    SetJobState(JobState.Running);
                    break;

                case PSInvocationState.Stopped:
                    SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Failed:
                    SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true);
                    break;

                case PSInvocationState.Completed:
                    if (_runningInitScript)
                    {
                        // Begin running main script.
                        _runningInitScript = false;
                        RunScript();
                    }
                    else
                    {
                        SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true);
                    }
                    break;
                }
            };

            // Get script block to run.
            if (!string.IsNullOrEmpty(_filePath))
            {
                _sb = GetScriptBlockFromFile(_filePath, psCmdlet);
                if (_sb == null)
                {
                    throw new InvalidOperationException(Properties.Resources.ResourceManager.GetString("CannotParseScriptFile"));
                }
            }
            else if (_sb == null)
            {
                throw new PSArgumentNullException(Properties.Resources.ResourceManager.GetString("NoScriptToRun"));
            }

            // Get any using variables.
            var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>();

            if (usingAsts != null &&
                usingAsts.FirstOrDefault() != null)
            {
                // Get using variables as an array or dictionary, depending on PowerShell version.
                if (psCmdlet.Host.Version.Major >= 5)
                {
                    _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet);
                }
                else if (psCmdlet.Host.Version.Major == 3 || psCmdlet.Host.Version.Major == 4)
                {
                    _usingValuesArray = GetUsingValuesAsArray(usingAsts, psCmdlet);
                }
            }

            // Hook up data streams.
            this.Output = _output;
            this.Output.EnumeratorNeverBlocks = true;

            this.Error = _ps.Streams.Error;
            this.Error.EnumeratorNeverBlocks = true;

            this.Progress = _ps.Streams.Progress;
            this.Progress.EnumeratorNeverBlocks = true;

            this.Verbose = _ps.Streams.Verbose;
            this.Verbose.EnumeratorNeverBlocks = true;

            this.Warning = _ps.Streams.Warning;
            this.Warning.EnumeratorNeverBlocks = true;

            this.Debug = _ps.Streams.Debug;
            this.Debug.EnumeratorNeverBlocks = true;

            // Create the JobManager job definition and job specification, and add to the JobManager.
            ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name);
            Dictionary <string, object> parameterCollection = new Dictionary <string, object>();

            parameterCollection.Add("NewJob", this);
            var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection);
            var newJob           = psCmdlet.JobManager.NewJob(jobSpecification);

            System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job");
        }
Ejemplo n.º 34
0
        internal static void ContinueCommand(RemoteRunspace remoteRunspace, Pipeline cmd, PSHost host, bool inDebugMode, System.Management.Automation.ExecutionContext context)
        {
            RemotePipeline remotePipeline = cmd as RemotePipeline;

            if (remotePipeline != null)
            {
                using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
                {
                    PSInvocationSettings settings = new PSInvocationSettings()
                    {
                        Host = host
                    };

                    PSDataCollection<PSObject> input = new PSDataCollection<PSObject>();

                    CommandInfo commandInfo = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, context);
                    Command outDefaultCommand = new Command(commandInfo);
                    ps.AddCommand(outDefaultCommand);
                    IAsyncResult async = ps.BeginInvoke<PSObject>(input, settings, null, null);

                    RemoteDebugger remoteDebugger = remoteRunspace.Debugger as RemoteDebugger;
                    if (remoteDebugger != null)
                    {
                        // Update client with breakpoint information from pushed runspace.
                        // Information will be passed to the client via the Debugger.BreakpointUpdated event.
                        remoteDebugger.SendBreakpointUpdatedEvents();

                        if (!inDebugMode)
                        {
                            // Enter debug mode if remote runspace is in debug stop mode.
                            remoteDebugger.CheckStateAndRaiseStopEvent();
                        }
                    }

                    // Wait for debugged cmd to complete.
                    while (!remotePipeline.Output.EndOfPipeline)
                    {
                        remotePipeline.Output.WaitHandle.WaitOne();
                        while (remotePipeline.Output.Count > 0)
                        {
                            input.Add(remotePipeline.Output.Read());
                        }
                    }

                    input.Complete();
                    ps.EndInvoke(async);
                }
            }
        }
Ejemplo n.º 35
0
 private void ValidateAndThrowRunspaceOpenModuleLoadException(PowerShell pse, List<ErrorRecord> errors, bool startLifeCycleEventWritten, string moduleName, RunspaceOpenModuleLoadException exception)
 {
     if (this.InitialSessionState.ThrowOnRunspaceOpenError)
     {
         RunspaceOpenModuleLoadException exception2 = null;
         if (exception != null)
         {
             exception2 = exception;
         }
         else if ((pse.Streams.Error.Count > 0) || (errors.Count > 0))
         {
             ErrorRecord record;
             Exception exception3;
             PSDataCollection<ErrorRecord> datas = new PSDataCollection<ErrorRecord>();
             if (errors.Count > 0)
             {
                 record = errors[0];
                 exception3 = record.Exception;
                 foreach (ErrorRecord record2 in errors)
                 {
                     datas.Add(record2);
                 }
             }
             else
             {
                 record = pse.Streams.Error[0];
                 exception3 = record.Exception;
                 foreach (ErrorRecord record3 in pse.Streams.Error)
                 {
                     datas.Add(record3);
                 }
             }
             runspaceInitTracer.WriteLine("Runspace open failed while loading module '{0}': First error {1}", new object[] { moduleName, exception3 });
             exception2 = new RunspaceOpenModuleLoadException(moduleName, datas);
         }
         if (exception2 != null)
         {
             this.LogEngineHealthEvent(exception2);
             if (startLifeCycleEventWritten)
             {
                 MshLog.LogEngineLifecycleEvent(this._engine.Context, EngineState.Stopped);
             }
             base.SetRunspaceState(RunspaceState.Broken, exception2);
             base.RaiseRunspaceStateEvents();
             throw exception2;
         }
     }
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Process debugger command.
        /// </summary>
        /// <param name="command">Debugger PSCommand</param>
        /// <param name="output">Output</param>
        /// <returns>DebuggerCommandResults</returns>
        public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
        {
            CheckForValidateState();
            _detachCommand = false;

            if (command == null)
            {
                throw new PSArgumentNullException("command");
            }

            if (output == null)
            {
                throw new PSArgumentNullException("output");
            }

            if (!DebuggerStopped)
            {
                throw new PSInvalidOperationException(
                    DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
                    null,
                    Debugger.CannotProcessCommandNotStopped,
                    ErrorCategory.InvalidOperation,
                    null);
            }

            DebuggerCommandResults results = null;

            // Execute command on server.
            bool executionError = false;
            using (_psDebuggerCommand = GetNestedPowerShell())
            {
                foreach (var cmd in command.Commands)
                {
                    cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
                    _psDebuggerCommand.AddCommand(cmd);
                }

                PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>();
                internalOutput.DataAdded += (sender, args) =>
                    {
                        foreach (var item in internalOutput.ReadAll())
                        {
                            if (item == null) { return; }

                            DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand;
                            if (dbgCmd != null)
                            {
                                bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger);
                                results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger);
                            }
                            else if (item.BaseObject is DebuggerCommandResults)
                            {
                                results = item.BaseObject as DebuggerCommandResults;
                            }
                            else
                            {
                                output.Add(item);
                            }
                        }
                    };

                try
                {
                    _psDebuggerCommand.Invoke(null, internalOutput, null);
                }
                catch (Exception e)
                {
                    CommandProcessor.CheckForSevereException(e);

                    executionError = true;
                    RemoteException re = e as RemoteException;
                    if ((re != null) && (re.ErrorRecord != null))
                    {
                        // Allow the IncompleteParseException to throw so that the console
                        // can handle here strings and continued parsing.
                        if (re.ErrorRecord.CategoryInfo.Reason == typeof(IncompleteParseException).Name)
                        {
                            throw new IncompleteParseException(
                                (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : null,
                                re.ErrorRecord.FullyQualifiedErrorId);
                        }

                        // Allow the RemoteException and InvalidRunspacePoolStateException to propagate so that the host can
                        // clean up the debug session.
                        if ((re.ErrorRecord.CategoryInfo.Reason == typeof(InvalidRunspacePoolStateException).Name) ||
                            (re.ErrorRecord.CategoryInfo.Reason == typeof(RemoteException).Name))
                        {
                            throw new PSRemotingTransportException(
                                (re.ErrorRecord.Exception != null) ? re.ErrorRecord.Exception.Message : string.Empty);
                        }
                    }

                    // Allow all PSRemotingTransportException and RemoteException errors to propagate as this
                    // indicates a broken debug session.
                    if ((e is PSRemotingTransportException) || (e is RemoteException))
                    {
                        throw;
                    }

                    output.Add(
                        new PSObject(
                            new ErrorRecord(
                            e,
                            "DebuggerError",
                            ErrorCategory.InvalidOperation,
                            null)));
                }
            }

            executionError = executionError || _psDebuggerCommand.HadErrors;
            _psDebuggerCommand = null;

            // Special processing when the detach command is run.
            _detachCommand = (!executionError) && (command.Commands.Count > 0) && (command.Commands[0].CommandText.Equals("Detach", StringComparison.OrdinalIgnoreCase));

            return results ?? new DebuggerCommandResults(null, false);
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Default constructor for creating ServerPowerShellDrivers
        /// </summary>
        /// <param name="powershell">decoded powershell object</param>
        /// <param name="extraPowerShell">extra pipeline to be run after <paramref name="powershell"/> completes</param>
        /// <param name="noInput">whether there is input for this powershell</param>
        /// <param name="clientPowerShellId">the client powershell id</param>
        /// <param name="clientRunspacePoolId">the client runspacepool id</param>
        /// <param name="runspacePoolDriver">runspace pool driver 
        /// which is creating this powershell driver</param>
        /// <param name="apartmentState">apartment state for this powershell</param>
        /// <param name="hostInfo">host info using which the host for
        /// this powershell will be constructed</param>
        /// <param name="streamOptions">serialization options for the streams in this powershell</param>
        /// <param name="addToHistory">
        /// true if the command is to be added to history list of the runspace. false, otherwise.
        /// </param>
        /// <param name="rsToUse">
        /// If not null, this Runspace will be used to invoke Powershell.
        /// If null, the RunspacePool pointed by <paramref name="runspacePoolDriver"/> will be used.
        /// </param>
        /// <param name="output">
        /// If not null, this is used as another source of output sent to the client.
        /// </param>
        internal ServerPowerShellDriver(PowerShell powershell, PowerShell extraPowerShell, bool noInput, Guid clientPowerShellId,
            Guid clientRunspacePoolId, ServerRunspacePoolDriver runspacePoolDriver,
            ApartmentState apartmentState, HostInfo hostInfo, RemoteStreamOptions streamOptions,
            bool addToHistory, Runspace rsToUse, PSDataCollection<PSObject> output)
#endif
        {
            InstanceId = clientPowerShellId;
            RunspacePoolId = clientRunspacePoolId;
            RemoteStreamOptions = streamOptions;
#if !CORECLR // No ApartmentState In CoreCLR
            this.apartmentState = apartmentState;
#endif
            LocalPowerShell = powershell;
            _extraPowerShell = extraPowerShell;
            _localPowerShellOutput = new PSDataCollection<PSObject>();
            _noInput = noInput;
            _addToHistory = addToHistory;
            _psDriverInvoker = runspacePoolDriver;

            DataStructureHandler = runspacePoolDriver.DataStructureHandler.CreatePowerShellDataStructureHandler(clientPowerShellId, clientRunspacePoolId, RemoteStreamOptions, LocalPowerShell);
            _remoteHost = DataStructureHandler.GetHostAssociatedWithPowerShell(hostInfo, runspacePoolDriver.ServerRemoteHost);

            if (!noInput)
            {
                InputCollection = new PSDataCollection<object>();
                InputCollection.ReleaseOnEnumeration = true;
                InputCollection.IdleEvent += new EventHandler<EventArgs>(HandleIdleEvent);
            }

            RegisterPipelineOutputEventHandlers(_localPowerShellOutput);

            if (LocalPowerShell != null)
            {
                RegisterPowerShellEventHandlers(LocalPowerShell);
                _datasent[0] = false;
            }

            if (extraPowerShell != null)
            {
                RegisterPowerShellEventHandlers(extraPowerShell);
                _datasent[1] = false;
            }

            RegisterDataStructureHandlerEventHandlers(DataStructureHandler);

            // set the runspace pool and invoke this powershell
            if (null != rsToUse)
            {
                LocalPowerShell.Runspace = rsToUse;
                if (extraPowerShell != null)
                {
                    extraPowerShell.Runspace = rsToUse;
                }
            }
            else
            {
                LocalPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
                if (extraPowerShell != null)
                {
                    extraPowerShell.RunspacePool = runspacePoolDriver.RunspacePool;
                }
            }

            if (output != null)
            {
                output.DataAdded += (sender, args) =>
                    {
                        if (_localPowerShellOutput.IsOpen)
                        {
                            var items = output.ReadAll();
                            foreach (var item in items)
                            {
                                _localPowerShellOutput.Add(item);
                            }
                        }
                    };
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Execution of PowerShell value activity.
        /// PowerShell expression will be evaluated using PowerShell runspace and the value of Type T will be returned.
        /// </summary>
        /// <param name="context"></param>
        protected override void Execute(NativeActivityContext context)
        {
            Token[]        tokens;
            ParseError[]   errors;
            ScriptBlockAst exprAst = Parser.ParseInput(Expression, out tokens, out errors);

            bool hasErrorActionPreference = false;
            bool hasWarningPreference     = false;
            bool hasInformationPreference = false;

            // Custom activity participant tracker for updating debugger with current variables and sequence stop points.
            // Regex looks for debugger sequence points like: Expression="'3:5:WFFunc1'".
            // We specifically disallow TimeSpan values that look like sequence points: Expression="'00:00:01'".
            bool isDebugSequencePoint = (!string.IsNullOrEmpty(Expression) && (System.Text.RegularExpressions.Regex.IsMatch(Expression, @"^'\d+:\d+:\S+'$")) &&
                                         (typeof(T) != typeof(System.TimeSpan)));
            var dataProperties = context.DataContext.GetProperties();

            if (isDebugSequencePoint || (dataProperties.Count > 0))
            {
                System.Activities.Tracking.CustomTrackingRecord customRecord = new System.Activities.Tracking.CustomTrackingRecord("PSWorkflowCustomUpdateDebugVariablesTrackingRecord");
                foreach (System.ComponentModel.PropertyDescriptor property in dataProperties)
                {
                    if (String.Equals(property.Name, "ParameterDefaults", StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    Object value = property.GetValue(context.DataContext);
                    if (value != null)
                    {
                        object tempValue = value;

                        PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>;
                        if (collectionObject != null && collectionObject.Count == 1)
                        {
                            tempValue = collectionObject[0];
                        }

                        customRecord.Data.Add(property.Name, tempValue);
                    }
                }
                if (isDebugSequencePoint)
                {
                    customRecord.Data.Add("DebugSequencePoint", Expression);
                }
                context.Track(customRecord);
            }

            if (tokens != null)
            {
                foreach (Token token in tokens)
                {
                    VariableToken variable = token as VariableToken;

                    if (variable != null)
                    {
                        if (variable.Name.Equals("ErrorActionPreference", StringComparison.OrdinalIgnoreCase))
                        {
                            hasErrorActionPreference = true;
                        }
                        else if (variable.Name.Equals("WarningPreference", StringComparison.OrdinalIgnoreCase))
                        {
                            hasWarningPreference = true;
                        }
                        else if (variable.Name.Equals("InformationPreference", StringComparison.OrdinalIgnoreCase))
                        {
                            hasInformationPreference = true;
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(Expression))
            {
                throw new ArgumentException(ActivityResources.NullArgumentExpression);
            }


            if (_ci == null)
            {
                lock (syncroot)
                {
                    // Invoke using the CommandInfo for Invoke-Command directly, rather than going through
                    // command discovery (which is very slow).
                    if (_ci == null)
                    {
                        _ci = new CmdletInfo("Invoke-Command", typeof(Microsoft.PowerShell.Commands.InvokeCommandCommand));
                    }
                }
            }

            Collection <PSObject> returnedvalue;
            Runspace       runspace         = null;
            bool           borrowedRunspace = false;
            PSWorkflowHost workflowHost     = null;

            if (typeof(ScriptBlock).IsAssignableFrom(typeof(T)))
            {
                Result.Set(context, ScriptBlock.Create(Expression));
                return;
            }
            else if (typeof(ScriptBlock[]).IsAssignableFrom(typeof(T)))
            {
                Result.Set(context, new ScriptBlock[] { ScriptBlock.Create(Expression) });
                return;
            }

            PropertyDescriptorCollection col        = context.DataContext.GetProperties();
            HostParameterDefaults        hostValues = context.GetExtension <HostParameterDefaults>();

            // Borrow a runspace from the host if we're not trying to create a ScriptBlock.
            // If we are trying to create one, we need to keep it around so that it can be
            // invoked multiple times.
            if (hostValues != null)
            {
                workflowHost = hostValues.Runtime;
                try
                {
                    runspace         = workflowHost.UnboundedLocalRunspaceProvider.GetRunspace(null, 0, 0);
                    borrowedRunspace = true;
                }
                catch (Exception)
                {
                    // it is fine to catch generic exception here
                    // if the local runspace provider does not give us
                    // a runspace we will create one locally (fallback)
                }
            }

            if (runspace == null)
            {
                // Not running with the PowerShell workflow host so directly create the runspace...
                runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2());
                runspace.Open();
            }

            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
            {
                try
                {
                    ps.Runspace = runspace;

                    // Subscribe to DataAdding on the error stream so that we can add position tracking information
                    if (hostValues != null)
                    {
                        HostSettingCommandMetadata sourceCommandMetadata = hostValues.HostCommandMetadata;

                        CommandMetadataTable.TryAdd(ps.InstanceId, sourceCommandMetadata);
                        ps.Streams.Error.DataAdding += HandleErrorDataAdding;
                    }

                    // First, set the variables from the host defaults
                    if ((hostValues != null) && (hostValues.Parameters != null))
                    {
                        if (hostValues.Parameters.ContainsKey("PSCurrentDirectory"))
                        {
                            string path = hostValues.Parameters["PSCurrentDirectory"] as string;
                            if (path != null)
                            {
                                ps.Runspace.SessionStateProxy.Path.SetLocation(path);
                            }
                        }

                        foreach (string hostDefault in hostValues.Parameters.Keys)
                        {
                            string mappedHostDefault = hostDefault;

                            if (hostDefault.Equals("ErrorAction", StringComparison.OrdinalIgnoreCase))
                            {
                                if (hasErrorActionPreference)
                                {
                                    mappedHostDefault = "ErrorActionPreference";
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else if (hostDefault.Equals("WarningAction", StringComparison.OrdinalIgnoreCase))
                            {
                                if (hasWarningPreference)
                                {
                                    mappedHostDefault = "WarningPreference";
                                }
                                else
                                {
                                    continue;
                                }
                            }
                            else if (hostDefault.Equals("InformationAction", StringComparison.OrdinalIgnoreCase))
                            {
                                if (hasInformationPreference)
                                {
                                    mappedHostDefault = "InformationPreference";
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            object propertyValue = hostValues.Parameters[hostDefault];
                            if (propertyValue != null)
                            {
                                ps.Runspace.SessionStateProxy.PSVariable.Set(mappedHostDefault, propertyValue);
                            }
                        }
                    }

                    // Then, set the variables from the workflow
                    foreach (PropertyDescriptor p in col)
                    {
                        string name  = p.Name;
                        object value = p.GetValue(context.DataContext);

                        if (value != null)
                        {
                            object tempValue = value;

                            PSDataCollection <PSObject> collectionObject = value as PSDataCollection <PSObject>;

                            if (collectionObject != null && collectionObject.Count == 1)
                            {
                                tempValue = collectionObject[0];
                            }

                            ps.Runspace.SessionStateProxy.PSVariable.Set(name, tempValue);
                        }
                    }

                    ps.AddCommand(_ci).AddParameter("NoNewScope").AddParameter("ScriptBlock", ExpressionScriptBlock);


                    // If this needs to consume input, take it from the host stream.
                    PSDataCollection <PSObject> inputStream = null;
                    if (UseDefaultInput)
                    {
                        // Retrieve our host overrides
                        hostValues = context.GetExtension <HostParameterDefaults>();

                        if (hostValues != null)
                        {
                            Dictionary <string, object> incomingArguments = hostValues.Parameters;
                            if (incomingArguments.ContainsKey("Input"))
                            {
                                inputStream = incomingArguments["Input"] as PSDataCollection <PSObject>;
                            }
                        }
                    }

                    // Now invoke the pipeline
                    try
                    {
                        if (inputStream != null)
                        {
                            returnedvalue = ps.Invoke(inputStream);
                            inputStream.Clear();
                        }
                        else
                        {
                            returnedvalue = ps.Invoke();
                        }
                    }
                    catch (CmdletInvocationException cie)
                    {
                        if (cie.ErrorRecord != null && cie.ErrorRecord.Exception != null)
                        {
                            throw cie.InnerException;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                finally
                {
                    if (hostValues != null)
                    {
                        ps.Streams.Error.DataAdding -= HandleErrorDataAdding;
                        HostSettingCommandMetadata removedValue;
                        CommandMetadataTable.TryRemove(ps.InstanceId, out removedValue);
                    }

                    if (borrowedRunspace)
                    {
                        workflowHost.UnboundedLocalRunspaceProvider.ReleaseRunspace(runspace);
                    }
                    else
                    {
                        // This will be disposed  when the command is done with it.
                        runspace.Dispose();
                        runspace = null;
                    }
                }


                if (ps.Streams.Error != null && ps.Streams.Error.Count > 0)
                {
                    PSDataCollection <ErrorRecord> errorStream = null;

                    // Retrieve our host overrides
                    hostValues = context.GetExtension <HostParameterDefaults>();

                    if (hostValues != null)
                    {
                        Dictionary <string, object> incomingArguments = hostValues.Parameters;
                        if (incomingArguments.ContainsKey("PSError"))
                        {
                            errorStream = incomingArguments["PSError"] as PSDataCollection <ErrorRecord>;
                        }
                    }

                    if (errorStream != null && errorStream.IsOpen)
                    {
                        foreach (ErrorRecord record in ps.Streams.Error)
                        {
                            errorStream.Add(record);
                        }
                    }
                }

                T valueToReturn = default(T);
                if (returnedvalue != null && returnedvalue.Count > 0)
                {
                    try
                    {
                        if (returnedvalue.Count == 1)
                        {
                            if (returnedvalue[0] != null)
                            {
                                Object result     = returnedvalue[0];
                                Object baseObject = ((PSObject)result).BaseObject;
                                if (!(baseObject is PSCustomObject))
                                {
                                    result = baseObject;
                                }

                                // Try regular PowerShell conversion
                                valueToReturn = LanguagePrimitives.ConvertTo <T>(result);
                            }
                        }
                        else
                        {
                            valueToReturn = LanguagePrimitives.ConvertTo <T>(returnedvalue);
                        }
                    }
                    catch (PSInvalidCastException)
                    {
                        // Handle the special case of emitting a PSDataCollection - use its array constructor.
                        // This special case is why we aren't using PowerShell.Invoke<T>
                        if (typeof(T) == typeof(PSDataCollection <PSObject>))
                        {
                            Object tempValueToReturn = new PSDataCollection <PSObject>(
                                new List <PSObject> {
                                LanguagePrimitives.ConvertTo <PSObject>(returnedvalue[0])
                            });
                            valueToReturn = (T)tempValueToReturn;
                        }
                        else
                        {
                            throw;
                        }
                    }

                    Result.Set(context, valueToReturn);
                }
            }
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Write
 /// </summary>
 /// <param name="value"></param>
 public override void Write(string value)
 {
     _output.Add(
         new PSObject(value));
 }
Ejemplo n.º 40
0
		private static void BeginSetVariablesInRemoteRunspace(RunCommandsArguments args)
		{
			Runspace runspace = args.ImplementationContext.PowerShellInstance.Runspace;
			PSActivityEnvironment pSActivityEnvironment = args.ImplementationContext.PSActivityEnvironment;
			PowerShellTraceSource traceSource = PowerShellTraceSourceFactory.GetTraceSource();
			using (traceSource)
			{
				traceSource.WriteMessage("BEGIN BeginSetVariablesInRemoteRunspace");
				PowerShell powerShell = PowerShell.Create();
				powerShell.Runspace = runspace;
				powerShell.AddScript("\r\n            Get-Variable -Exclude input | Remove-Variable 2> $Null;$error.Clear();$input | Foreach-Object {$nvp=$_}; foreach($k in $nvp.keys){set-variable -name $k -value $nvp[$k]}\r\n        ");
				Dictionary<string, object> variablesToSetInRunspace = PSActivity.GetVariablesToSetInRunspace(pSActivityEnvironment);
				PSDataCollection<object> objs = new PSDataCollection<object>();
				objs.Add(variablesToSetInRunspace);
				PSDataCollection<object> objs1 = objs;
				objs1.Complete();
				args.HelperCommand = powerShell;
				args.HelperCommandInput = objs1;
				PSActivity.BeginInvokeOnPowershellCommand(powerShell, objs1, null, new AsyncCallback(PSActivity.SetVariablesCallback), args);
				traceSource.WriteMessage("END BeginSetVariablesInRemoteRunspace");
			}
		}
Ejemplo n.º 41
0
 /// <summary>
 /// WriteErrorLine
 /// </summary>
 /// <param name="value"></param>
 public override void WriteErrorLine(string value)
 {
     _error.Add(
         new ErrorRecord(new RuntimeException(value), null, ErrorCategory.NotSpecified, null));
 }
Ejemplo n.º 42
0
		protected void WriteProgressRecord(NativeActivityContext context, PSDataCollection<ProgressRecord> progress, string statusDescription, ProgressRecordType type)
		{
			string displayName;
			int num = 0;
			if (progress != null)
			{
				string str = null;
				if (this.PSProgressMessage != null)
				{
					str = this.PSProgressMessage.Get(context);
					if (this.PSProgressMessage.Expression != null && string.IsNullOrEmpty(str))
					{
						return;
					}
				}
				if (str != null)
				{
					displayName = string.Concat(base.DisplayName, ": ", str);
				}
				else
				{
					displayName = base.DisplayName;
					if (string.IsNullOrEmpty(displayName))
					{
						displayName = base.GetType().Name;
					}
				}
				ProgressRecord progressRecord = new ProgressRecord(0, displayName, statusDescription);
				progressRecord.RecordType = type;
				string str1 = string.Concat(base.Id, ":");
				HostParameterDefaults extension = context.GetExtension<HostParameterDefaults>();
				if (extension != null)
				{
					HostSettingCommandMetadata hostCommandMetadata = extension.HostCommandMetadata;
					if (hostCommandMetadata != null)
					{
						object[] commandName = new object[3];
						commandName[0] = hostCommandMetadata.CommandName;
						commandName[1] = hostCommandMetadata.StartLineNumber;
						commandName[2] = hostCommandMetadata.StartColumnNumber;
						str1 = string.Concat(str1, string.Format(CultureInfo.CurrentCulture, Resources.ProgressPositionMessage, commandName));
					}
				}
				progressRecord.CurrentOperation = str1;
				foreach (PropertyDescriptor property in context.DataContext.GetProperties())
				{
					if (!string.Equals(property.DisplayName, "PSParentActivityID", StringComparison.OrdinalIgnoreCase))
					{
						if (!string.Equals(property.DisplayName, "ProgressPreference", StringComparison.OrdinalIgnoreCase))
						{
							continue;
						}
						string value = property.GetValue(context.DataContext) as string;
						if (string.IsNullOrEmpty(value) || !string.Equals(value, "SilentlyContinue", StringComparison.OrdinalIgnoreCase) && !string.Equals(value, "Ignore", StringComparison.OrdinalIgnoreCase))
						{
							continue;
						}
						return;
					}
					else
					{
						object obj = property.GetValue(context.DataContext);
						if (obj == null || !LanguagePrimitives.TryConvertTo<int>(obj, CultureInfo.InvariantCulture, out num))
						{
							continue;
						}
						progressRecord.ParentActivityId = num;
					}
				}
				progress.Add(progressRecord);
				return;
			}
			else
			{
				return;
			}
		}
Ejemplo n.º 43
0
        /// <summary>
        /// ProcessCommand
        /// </summary>
        /// <param name="command">PowerShell command</param>
        /// <param name="output">Output</param>
        /// <returns>DebuggerCommandResults</returns>
        public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataCollection<PSObject> output)
        {
            if (command == null)
            {
                throw new PSArgumentNullException("command");
            }

            if (output == null)
            {
                throw new PSArgumentNullException("output");
            }

            if (!DebuggerStopped)
            {
                throw new PSInvalidOperationException(
                    DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
                    null,
                    Debugger.CannotProcessCommandNotStopped,
                    ErrorCategory.InvalidOperation,
                    null);
            }

            //
            // Allow an active pushed debugger to process commands
            //
            DebuggerCommandResults results = ProcessCommandForActiveDebugger(command, output);
            if (results != null)
            {
                return results;
            }

            //
            // Otherwise let root script debugger handle it.
            //
            LocalRunspace localRunspace = _context.CurrentRunspace as LocalRunspace;
            if (localRunspace == null)
            {
                throw new PSInvalidOperationException(
                    DebuggerStrings.CannotProcessDebuggerCommandNotStopped,
                    null,
                    Debugger.CannotProcessCommandNotStopped,
                    ErrorCategory.InvalidOperation,
                    null);
            }

            try
            {
                using (_psDebuggerCommand = PowerShell.Create())
                {
                    if (localRunspace.GetCurrentlyRunningPipeline() != null)
                    {
                        _psDebuggerCommand.SetIsNested(true);
                    }
                    _psDebuggerCommand.Runspace = localRunspace;
                    _psDebuggerCommand.Commands = command;
                    foreach (var cmd in _psDebuggerCommand.Commands.Commands)
                    {
                        cmd.MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
                    }

                    PSDataCollection<PSObject> internalOutput = new PSDataCollection<PSObject>();
                    internalOutput.DataAdded += (sender, args) =>
                        {
                            foreach (var item in internalOutput.ReadAll())
                            {
                                if (item == null) { continue; }

                                DebuggerCommand dbgCmd = item.BaseObject as DebuggerCommand;
                                if (dbgCmd != null)
                                {
                                    bool executedByDebugger = (dbgCmd.ResumeAction != null || dbgCmd.ExecutedByDebugger);
                                    results = new DebuggerCommandResults(dbgCmd.ResumeAction, executedByDebugger);
                                }
                                else
                                {
                                    output.Add(item);
                                }
                            }
                        };

                    // Allow any exceptions to propagate.
                    _psDebuggerCommand.InvokeWithDebugger(null, internalOutput, null, false);
                }
            }
            finally
            {
                _psDebuggerCommand = null;
            }

            return results ?? new DebuggerCommandResults(null, false);
        }
Ejemplo n.º 44
0
		private void SortStartParameters(DynamicActivity dynamicActivity, CommandParameterCollection parameters)
		{
			uint num = 0;
			bool flag;
			bool flag1;
			string str;
			object baseObject;
			if (dynamicActivity == null)
			{
				flag = false;
			}
			else
			{
				flag = dynamicActivity.Properties.Contains("PSComputerName");
			}
			bool flag2 = flag;
			if (dynamicActivity == null)
			{
				flag1 = false;
			}
			else
			{
				flag1 = dynamicActivity.Properties.Contains("PSPrivateMetadata");
			}
			bool flag3 = flag1;
			this._jobMetadata.Add("WorkflowTakesPrivateMetadata", flag3);
			if (parameters != null)
			{
				foreach (CommandParameter parameter in parameters)
				{
					PowerShellTraceSource powerShellTraceSource = this._tracer;
					string str1 = "PSWorkflowJob";
					string str2 = "SortStartParameters";
					Guid workflowGuidForTraces = this.WorkflowGuidForTraces;
					PSWorkflowJob pSWorkflowJob = this;
					string str3 = "Found parameter; {0}; {1}";
					string[] name = new string[2];
					name[0] = parameter.Name;
					string[] strArrays = name;
					int num1 = 1;
					if (parameter.Value == null)
					{
						str = null;
					}
					else
					{
						str = parameter.Value.ToString();
					}
					strArrays[num1] = str;
					powerShellTraceSource.WriteMessage(str1, str2, workflowGuidForTraces, pSWorkflowJob, str3, name);
					string name1 = parameter.Name;
					string str4 = name1;
					if (name1 != null)
					{
						if (str4 == "PSComputerName")
						{
							if (!flag2)
							{
								string value = parameter.Value as string;
								this._location = value;
								string[] strArrays1 = LanguagePrimitives.ConvertTo<string[]>(parameter.Value);
								this._psWorkflowCommonParameters[parameter.Name] = strArrays1;
								PSSQMAPI.NoteWorkflowCommonParametersValues(parameter.Name, (int)strArrays1.Length);
								continue;
							}
							else
							{
								this._location = "localhost";
								this._workflowParameters[parameter.Name] = LanguagePrimitives.ConvertTo<string[]>(parameter.Value);
								continue;
							}
						}
						else if (str4 == "PSPrivateMetadata")
						{
							Hashtable hashtables = parameter.Value as Hashtable;
							if (hashtables == null)
							{
								continue;
							}
							IDictionaryEnumerator enumerator = hashtables.GetEnumerator();
							while (enumerator.MoveNext())
							{
								this._privateMetadata.Add(enumerator.Key.ToString(), enumerator.Value);
							}
							if (flag3)
							{
								this._workflowParameters.Add(parameter.Name, parameter.Value);
							}
							PSSQMAPI.NoteWorkflowCommonParametersValues(parameter.Name, hashtables.Count);
							continue;
						}
						else if (str4 == "PSInputCollection")
						{
							if (parameter.Value as PSObject != null)
							{
								baseObject = ((PSObject)parameter.Value).BaseObject;
							}
							else
							{
								baseObject = parameter.Value;
							}
							object obj = baseObject;
							if (obj as PSDataCollection<PSObject> == null)
							{
								PSDataCollection<PSObject> pSObjects = new PSDataCollection<PSObject>();
								IEnumerator enumerator1 = LanguagePrimitives.GetEnumerator(obj);
								if (enumerator1 == null)
								{
									pSObjects.Add(PSObject.AsPSObject(parameter.Value));
								}
								else
								{
									while (enumerator1.MoveNext())
									{
										pSObjects.Add(PSObject.AsPSObject(enumerator1.Current));
									}
								}
								this._inputCollection = pSObjects;
								continue;
							}
							else
							{
								this._inputCollection = obj as PSDataCollection<PSObject>;
								continue;
							}
						}
						else if (str4 == "PSParameterCollection")
						{
							continue;
						}
						else if (str4 == "PSRunningTimeoutSec" || str4 == "PSElapsedTimeoutSec" || str4 == "PSConnectionRetryCount" || str4 == "PSActionRetryCount" || str4 == "PSConnectionRetryIntervalSec" || str4 == "PSActionRetryIntervalSec")
						{
							this._psWorkflowCommonParameters.Add(parameter.Name, parameter.Value);
							if (!LanguagePrimitives.TryConvertTo<uint>(parameter.Value, out num))
							{
								continue;
							}
							PSSQMAPI.NoteWorkflowCommonParametersValues(parameter.Name, num);
							continue;
						}
						else if (str4 == "PSPersist" || str4 == "PSCredential" || str4 == "PSPort" || str4 == "PSUseSSL" || str4 == "PSConfigurationName" || str4 == "PSApplicationName" || str4 == "PSConnectionURI" || str4 == "PSSessionOption" || str4 == "PSAuthentication" || str4 == "PSAuthenticationLevel" || str4 == "PSCertificateThumbprint" || str4 == "PSAllowRedirection" || str4 == "Verbose" || str4 == "Debug" || str4 == "ErrorAction" || str4 == "WarningAction" || str4 == "PSWorkflowErrorAction")
						{
							this._psWorkflowCommonParameters.Add(parameter.Name, parameter.Value);
							PSSQMAPI.IncrementWorkflowCommonParameterPresent(parameter.Name);
							continue;
						}
						else if (str4 == "PSSenderInfo" || str4 == "PSWorkflowRoot" || str4 == "PSCurrentDirectory")
						{
							this._psWorkflowCommonParameters.Add(parameter.Name, parameter.Value);
							continue;
						}
					}
					this._workflowParameters.Add(parameter.Name, parameter.Value);
					if (parameter.Value == null)
					{
						continue;
					}
					PSSQMAPI.IncrementWorkflowSpecificParameterType(parameter.Value.GetType());
				}
			}
			this._psWorkflowCommonParameters.Add("WorkflowCommandName", this._definition.Command);
		}
Ejemplo n.º 45
0
        /// <summary>
        /// Create necessary dictionaries for WorkflowManager consumption based on StartParameters.
        /// </summary>
        private void SortStartParameters(DynamicActivity dynamicActivity, CommandParameterCollection parameters)
        {
            bool selfRemoting = dynamicActivity != null && dynamicActivity.Properties.Any(x => x.Name.Equals(Constants.ComputerName, StringComparison.CurrentCultureIgnoreCase));
            bool takesPSPrivateMetadata = dynamicActivity != null && dynamicActivity.Properties.Contains(Constants.PrivateMetadata);
            _jobMetadata.Add(Constants.WorkflowTakesPrivateMetadata, takesPSPrivateMetadata);

            if (parameters != null)
            {
                foreach (var parameter in parameters)
                {
                    _tracer.WriteMessage(ClassNameTrace, "SortStartParameters", WorkflowGuidForTraces, this, "Found parameter; {0}; {1}", parameter.Name,
                        parameter.Value == null ? null : parameter.Value.ToString());
                    switch (parameter.Name)
                    {
                        case Constants.ComputerName:
                            if (selfRemoting)
                            {
                                // If we're self-remoting, location becomes the default computer
                                // and the PSComputerNames is passed in as an argument instead
                                // of going to the ubiquitous parameters
                                _location = Constants.DefaultComputerName;
                                string parameterName = dynamicActivity.Properties.First(x => x.Name.Equals(Constants.ComputerName, StringComparison.CurrentCultureIgnoreCase)).Name;
                                _workflowParameters[parameterName] = LanguagePrimitives.ConvertTo<string[]>(parameter.Value);
                            }
                            else
                            {
                                // Set _location before adding parameter.
                                var computer = parameter.Value as string;
                                _location = computer;
                                string[] computerNames = LanguagePrimitives.ConvertTo<string[]>(parameter.Value);
                                _psWorkflowCommonParameters[parameter.Name] = computerNames;
                            }
                            break;
                        case Constants.PrivateMetadata:
                            Hashtable privateData = parameter.Value as Hashtable;
                            if (privateData != null)
                            {
                                IDictionaryEnumerator enumerator = privateData.GetEnumerator();
                                while (enumerator.MoveNext())
                                {
                                    _privateMetadata.Add(enumerator.Key.ToString(), enumerator.Value);
                                }

                                // Make the combined object available within the workflow as well...
                                if (takesPSPrivateMetadata)
                                {
                                    _workflowParameters.Add(parameter.Name, parameter.Value);
                                }
                            }
                            break;

                        case Constants.PSInputCollection:
                            {
                                // Remove the input collection so we can properly pass it to the workflow job
                                object baseObject = parameter.Value is PSObject
                                                        ? ((PSObject)parameter.Value).BaseObject
                                                        : parameter.Value;

                                if (baseObject is PSDataCollection<PSObject>)
                                {
                                    _inputCollection = baseObject as PSDataCollection<PSObject>;
                                }
                                else
                                {
                                    var inputCollection = new PSDataCollection<PSObject>();
                                    var e = LanguagePrimitives.GetEnumerator(baseObject);
                                    if (e != null)
                                    {
                                        while (e.MoveNext())
                                        {
                                            inputCollection.Add(PSObject.AsPSObject(e.Current));
                                        }
                                    }
                                    else
                                    {
                                        inputCollection.Add(PSObject.AsPSObject(parameter.Value));
                                    }
                                    _inputCollection = inputCollection;
                                }
                            }
                            break;

                        case Constants.PSParameterCollection:
                            // Remove this one from the parameter collection...
                            break;
                        case Constants.PSRunningTime:
                        case Constants.PSElapsedTime:
                        case Constants.ConnectionRetryCount:
                        case Constants.ActionRetryCount:
                        case Constants.ConnectionRetryIntervalSec:
                        case Constants.ActionRetryIntervalSec:
                            _psWorkflowCommonParameters.Add(parameter.Name, parameter.Value);
                            break;

                        case Constants.Persist:
                        case Constants.Credential:
                        case Constants.Port:
                        case Constants.UseSSL:
                        case Constants.ConfigurationName:
                        case Constants.ApplicationName:
                        case Constants.ConnectionURI:
                        case Constants.SessionOption:
                        case Constants.Authentication:
                        case Constants.AuthenticationLevel:
                        case Constants.CertificateThumbprint:
                        case Constants.AllowRedirection:
                        case Constants.Verbose:
                        case Constants.Debug:
                        case Constants.ErrorAction:
                        case Constants.WarningAction:
                        case Constants.InformationAction:
                        case Constants.PSWorkflowErrorAction:
                        case Constants.PSSuspendOnError:
                        case Constants.PSSenderInfo:
                        case Constants.ModulePath:
                        case Constants.PSCurrentDirectory:
                            // Note: We don't add ErrorVariable, WarningVariable, OutVariable, or OutBuffer
                            // here because they are interpreted by PowerShell in the function generated over
                            // the workflow definition.
                            _psWorkflowCommonParameters.Add(parameter.Name, parameter.Value);
                            break;
                        default:
                            _workflowParameters.Add(parameter.Name, parameter.Value);
                            break;
                    }
                }
            }

            // Add in the workflow command name...
            _psWorkflowCommonParameters.Add("WorkflowCommandName", _definition.Command);
        }
Ejemplo n.º 46
0
        private void ReportException(Exception e)
        {
            if (e != null)
            {
                object error;
                IContainsErrorRecord icer = e as IContainsErrorRecord;
                if (icer != null)
                {
                    error = icer.ErrorRecord;
                }
                else
                {
                    error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
                }

                lock (this.instanceLock)
                {
                    this.currentPowerShell = PowerShell.Create();
                }

                this.currentPowerShell.Runspace = this.myRunSpace;

                try
                {
                    this.currentPowerShell.AddScript("$input").AddCommand("out-string");

                    Collection<PSObject> result;
                    PSDataCollection<object> inputCollection = new PSDataCollection<object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = this.currentPowerShell.Invoke(inputCollection);

                    if (result.Count > 0)
                    {
                        string str = result[0].BaseObject as string;
                        if (!string.IsNullOrEmpty(str))
                        { 
                            this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
                finally
                {
                    lock (this.instanceLock)
                    {
                        this.currentPowerShell.Dispose();
                        this.currentPowerShell = null;
                    }
                }
            }
        }
Ejemplo n.º 47
0
        /// <summary>
        /// To display an exception using the display formatter, 
        /// run a second pipeline passing in the error record.
        /// The runtime will bind this to the $input variable,
        /// which is why $input is being piped to the Out-String
        /// cmdlet. The WriteErrorLine method is called to make sure 
        /// the error gets displayed in the correct error color.
        /// </summary>
        /// <param name="e">The exception to display.</param>
        private void ReportException(Exception e)
        {
            if (e != null)
            {
                object error;
                IContainsErrorRecord icer = e as IContainsErrorRecord;
                if (icer != null)
                {
                    error = icer.ErrorRecord;
                }
                else
                {
                    error = (object)new ErrorRecord(e, "Host.ReportException", ErrorCategory.NotSpecified, null);
                }

                lock (this.instanceLock)
                {
                    this.currentPowerShell = PowerShell.Create();
                }

                this.currentPowerShell.Runspace = this.myRunSpace;

                try
                {
                    this.currentPowerShell.AddScript("$input").AddCommand("out-string");

                    // Do not merge errors, this function will swallow errors.
                    Collection<PSObject> result;
                    PSDataCollection<object> inputCollection = new PSDataCollection<object>();
                    inputCollection.Add(error);
                    inputCollection.Complete();
                    result = this.currentPowerShell.Invoke(inputCollection);

                    if (result.Count > 0)
                    {
                        string str = result[0].BaseObject as string;
                        if (!string.IsNullOrEmpty(str))
                        {
                            // Remove \r\n, which is added by the Out-String cmdlet.
                            this.myHost.UI.WriteErrorLine(str.Substring(0, str.Length - 2));
                        }
                    }
                }
                finally
                {
                    // Dispose of the pipeline and set it to null, locking it  because
                    // currentPowerShell may be accessed by the ctrl-C handler.
                    lock (this.instanceLock)
                    {
                        this.currentPowerShell.Dispose();
                        this.currentPowerShell = null;
                    }
                }
            }
        }
        private void OnData(object sender, NotifyCollectionChangedEventArgs e)
        {
            if( e.Action != NotifyCollectionChangedAction.Add)
            {
                return;
            }

            PSDataCollection<object> input = new PSDataCollection<object>();
            foreach (var ci in e.NewItems)
            {
                input.Add(ci);
            }

            Interlocked.Exchange( ref _currentInput, input );
            RaiseTrigger();
        }