コード例 #1
0
 public IEnumerable <PSObject> Invoke()
 {
     if (!this.asyncInvoke)
     {
         Collection <PSObject> result = null;
         using (RunspaceProxy runspaceProxy = new RunspaceProxy(this.runspaceMediator, true))
         {
             IPowerShellProxy powerShellProxy = ProxyPSCommand.PowerShellProxyFactory(runspaceProxy, this.cmd);
             result = powerShellProxy.Invoke <PSObject>();
             if (powerShellProxy.Errors != null && powerShellProxy.Errors.Count != 0 && powerShellProxy.Errors[0].Exception != null)
             {
                 throw powerShellProxy.Errors[0].Exception;
             }
             if (powerShellProxy.Warnings != null && powerShellProxy.Warnings.Count != 0)
             {
                 foreach (WarningRecord warningRecord in powerShellProxy.Warnings)
                 {
                     this.writeWarning(new LocalizedString(warningRecord.Message));
                 }
             }
         }
         return(result);
     }
     return(new CmdletProxyDataReader(this.runspaceMediator, this.cmd, this.writeWarning));
 }
コード例 #2
0
        public PoshConsole()
        {
            // Initialize the document.
            // If they set it themselves, that's fine, but we have to make sure there is one!
            var document = new FlowDocument();

            document.Blocks.Add(new Paragraph {
                ClearFloaters = WrapDirection.Both
            });
            var consoleFont = new Style();

            consoleFont.Setters.Add(new Setter(TextElement.FontSizeProperty, 12));
            consoleFont.Setters.Add(new Setter(TextElement.FontFamilyProperty, "Consolas"));
            document.Resources.Add("ConsoleFont", consoleFont);
            Document = document;

            Runner = new RunspaceProxy(_host);
            Runner.RunspaceReady += (source, args) => Dispatcher.BeginInvoke((Action)(() =>
            {
                CommandBox.IsEnabled = true;
                OnCommandFinished(null, PipelineState.Completed);
            }));

            // TODO: Improve this interface
            Expander.TabComplete = Runner.CompleteInput;
            CurrentConsole       = this;
        }
コード例 #3
0
ファイル: PoshConsole.cs プロジェクト: Jaykul/PoshConsole
        public PoshConsole()
        {
            // Initialize the document.
            // If they set it themselves, that's fine, but we have to make sure there is one!
            var document = new FlowDocument();

            document.Blocks.Add(new Paragraph { ClearFloaters = WrapDirection.Both });
            var consoleFont = new Style();
            consoleFont.Setters.Add(new Setter(TextElement.FontSizeProperty, 12));
            consoleFont.Setters.Add(new Setter(TextElement.FontFamilyProperty, "Consolas"));
            document.Resources.Add("ConsoleFont", consoleFont);
            Document = document;

            Runner = new RunspaceProxy(_host);
            Runner.RunspaceReady += (source, args) => Dispatcher.BeginInvoke((Action)(() =>
            {
                CommandBox.IsEnabled = true;
                OnCommandFinished(null, PipelineState.Completed);
            }));

            // TODO: Improve this interface
            Expander.TabComplete = Runner.CompleteInput;
            CurrentConsole = this;
        }
コード例 #4
0
 // Token: 0x060010BB RID: 4283 RVA: 0x00033480 File Offset: 0x00031680
 public MonadPipelineProxy(RunspaceProxy proxy, IEnumerable input, PSCommand commands, WorkUnit[] workUnits) : base(proxy, workUnits, commands)
 {
     this.InitInput(input);
 }
コード例 #5
0
 // Token: 0x060010BA RID: 4282 RVA: 0x0003346F File Offset: 0x0003166F
 public MonadPipelineProxy(RunspaceProxy proxy, IEnumerable input, PSCommand commands) : this(proxy, commands)
 {
     this.InitInput(input);
 }
コード例 #6
0
 // Token: 0x060010B9 RID: 4281 RVA: 0x00033465 File Offset: 0x00031665
 public MonadPipelineProxy(RunspaceProxy proxy, PSCommand commands) : base(proxy, commands)
 {
 }
コード例 #7
0
        private static PowerShellResults <O> InvokeCore <O>(PSCommand psCommand, RunspaceMediator runspaceMediator, IEnumerable pipelineInput, WebServiceParameters parameters, CmdletActivity activity, bool isGetListAsync)
        {
            Func <WarningRecord, string> func  = null;
            Func <Command, string>       func2 = null;

            PSCommandExtension.EnsureNoWriteTaskInGetRequest(psCommand, parameters);
            PowerShellResults <O> powerShellResults = new PowerShellResults <O>();

            ExTraceGlobals.EventLogTracer.TraceInformation <string, EcpTraceFormatter <PSCommand> >(0, 0L, "{0} tries to invoke {1}. For more details, refer to task trace", RbacPrincipal.Current.NameForEventLog, psCommand.GetTraceFormatter());
            using (RunspaceProxy runspaceProxy = new RunspaceProxy(runspaceMediator))
            {
                runspaceProxy.SetVariable("ConfirmPreference", "None");
                if (parameters != null)
                {
                    psCommand.AddParameters(parameters);
                }
                using (PowerShell powerShell = runspaceProxy.CreatePowerShell(psCommand))
                {
                    List <PSObject> list = null;
                    if (activity != null)
                    {
                        AsyncServiceManager.RegisterPowerShellToActivity(powerShell, activity, pipelineInput, out list, isGetListAsync);
                    }
                    else
                    {
                        AsyncServiceManager.RegisterPowerShell(powerShell);
                    }
                    int      requestLatency = 0;
                    DateTime utcNow         = DateTime.UtcNow;
                    try
                    {
                        TaskPerformanceRecord taskPerformanceRecord = new TaskPerformanceRecord(psCommand.GetCmdletName(), PSCommandExtension.powerShellLatencyDetectionContextFactory, EcpEventLogConstants.Tuple_EcpPowerShellInvoked, EcpEventLogConstants.Tuple_EcpPowerShellCompleted, EcpEventLogExtensions.EventLog, new IPerformanceDataProvider[]
                        {
                            PerformanceContext.Current,
                            RpcDataProvider.Instance,
                            TaskPerformanceData.CmdletInvoked,
                            TaskPerformanceData.BeginProcessingInvoked,
                            TaskPerformanceData.ProcessRecordInvoked,
                            TaskPerformanceData.EndProcessingInvoked,
                            EcpPerformanceData.PowerShellInvoke
                        });
                        try
                        {
                            using (EcpPerformanceData.PowerShellInvoke.StartRequestTimer())
                            {
                                if (list == null)
                                {
                                    powerShellResults.Output = powerShell.Invoke <O>(pipelineInput).ToArray <O>();
                                }
                                else
                                {
                                    powerShell.Invoke <PSObject>(pipelineInput, list);
                                    powerShellResults.Output = Array <O> .Empty;
                                }
                            }
                        }
                        finally
                        {
                            requestLatency = (int)taskPerformanceRecord.Stop().TotalMilliseconds;
                            IDisposable disposable2 = taskPerformanceRecord;
                            if (disposable2 != null)
                            {
                                disposable2.Dispose();
                            }
                        }
                        List <ErrorRecord> list2 = new List <ErrorRecord>();
                        bool flag = false;
                        foreach (ErrorRecord errorRecord in powerShell.Streams.Error)
                        {
                            if (!flag)
                            {
                                flag = PSCommandExtension.TryPatchShouldContinueException(errorRecord, psCommand, parameters);
                            }
                            list2.Add(new ErrorRecord(errorRecord));
                        }
                        powerShellResults.ErrorRecords = list2.ToArray();
                        PowerShellResults           powerShellResults2 = powerShellResults;
                        IEnumerable <WarningRecord> warning            = powerShell.Streams.Warning;
                        if (func == null)
                        {
                            func = ((WarningRecord warningRecord) => warningRecord.Message);
                        }
                        powerShellResults2.Warnings = warning.Select(func).ToArray <string>();
                    }
                    catch (RuntimeException ex)
                    {
                        PSCommandExtension.TryPatchShouldContinueException(ex.ErrorRecord, psCommand, parameters);
                        ErrorRecord errorRecord2;
                        if (ex.ErrorRecord != null && !(ex is ParameterBindingException))
                        {
                            errorRecord2 = new ErrorRecord(ex.ErrorRecord);
                        }
                        else
                        {
                            errorRecord2 = new ErrorRecord(ex);
                        }
                        powerShellResults.ErrorRecords = new ErrorRecord[]
                        {
                            errorRecord2
                        };
                    }
                    finally
                    {
                        string         text     = HttpContext.Current.Request.QueryString["reqId"];
                        ServerLogEvent logEvent = new ServerLogEvent(psCommand, pipelineInput, requestLatency, string.IsNullOrEmpty(text) ? string.Empty : text, (powerShellResults.ErrorRecords != null && powerShellResults.ErrorRecords.Length > 0) ? powerShellResults.ErrorRecords.ToLogString() : string.Empty, (powerShellResults.Output != null) ? powerShellResults.Output.Length : 0);
                        ServerLogger.Instance.LogEvent(logEvent);
                    }
                    PowerShellResults     powerShellResults3 = powerShellResults;
                    IEnumerable <Command> commands           = psCommand.Commands;
                    if (func2 == null)
                    {
                        func2 = ((Command cmd) => cmd.CommandText);
                    }
                    powerShellResults3.Cmdlets = commands.Select(func2).ToArray <string>();
                    if (powerShellResults.ErrorRecords.Length > 0)
                    {
                        ExTraceGlobals.EventLogTracer.TraceError <string, EcpTraceFormatter <PSCommand>, EcpTraceFormatter <ErrorRecord[]> >(0, 0L, "{0} invoked {1} and encountered errors: {2}", RbacPrincipal.Current.NameForEventLog, psCommand.GetTraceFormatter(), powerShellResults.ErrorRecords.GetTraceFormatter());
                    }
                    CmdExecuteInfo cmdExecuteInfo = CmdletLogger.CaculateLogAndSaveToContext(powerShell, utcNow, powerShellResults.ErrorRecords);
                    if (cmdExecuteInfo != null)
                    {
                        powerShellResults.CmdletLogInfo = new CmdExecuteInfo[]
                        {
                            cmdExecuteInfo
                        };
                    }
                }
            }
            return(powerShellResults);
        }
コード例 #8
0
        internal static void PropagateExchangePropertyContainer(ISessionState sessionState, RunspaceProxy runspace, bool propagateRBAC, bool propagateBudget, ADServerSettings adServerSettingsOverride, ExchangeRunspaceConfigurationSettings.ExchangeApplication application)
        {
            ExchangePropertyContainer propertyContainer         = ExchangePropertyContainer.GetPropertyContainer(sessionState);
            ExchangePropertyContainer exchangePropertyContainer = new ExchangePropertyContainer();

            if (propertyContainer.exchangeRunspaceConfiguration != null)
            {
                propertyContainer.exchangeRunspaceConfiguration.TryGetExecutingUserId(out exchangePropertyContainer.executingUserId);
                exchangePropertyContainer.executingUserOrganizationId = propertyContainer.exchangeRunspaceConfiguration.OrganizationId;
                if (propagateRBAC)
                {
                    exchangePropertyContainer.exchangeRunspaceConfiguration = propertyContainer.exchangeRunspaceConfiguration;
                }
                exchangePropertyContainer.propagatedClientAppId = application;
                if (propertyContainer.budget != null && propagateBudget)
                {
                    exchangePropertyContainer.budget = ExchangePropertyContainer.AcquirePowerShellBudget(propertyContainer.exchangeRunspaceConfiguration);
                }
            }
            else
            {
                exchangePropertyContainer.executingUserId             = propertyContainer.executingUserId;
                exchangePropertyContainer.executingUserOrganizationId = propertyContainer.executingUserOrganizationId;
            }
            exchangePropertyContainer.logEntries = propertyContainer.logEntries;
            exchangePropertyContainer.logEnabled = propertyContainer.logEnabled;
            if (adServerSettingsOverride == null)
            {
                exchangePropertyContainer.serverSettings = propertyContainer.serverSettings;
            }
            else
            {
                exchangePropertyContainer.serverSettings = adServerSettingsOverride;
            }
            runspace.SetVariable(ExchangePropertyContainer.ExchangePropertyContainerName, exchangePropertyContainer);
        }
コード例 #9
0
        public static PowerShellResults Invoke(this PSCommand psCommand, RunspaceMediator runspaceMediator)
        {
            PowerShellResults results = null;

            ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.InvokeCmdletLatency, delegate
            {
                using (RunspaceProxy runspace = new RunspaceProxy(runspaceMediator))
                {
                    try
                    {
                        ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.InvokeCmdletExcludeRunspaceCreationLatency, delegate
                        {
                            using (PowerShell powerShell = runspace.CreatePowerShell(psCommand))
                            {
                                try
                                {
                                    Collection <PSObject> output = null;
                                    ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.InvokeCmdletExclusiveLatency, delegate
                                    {
                                        output = powerShell.Invoke();
                                    });
                                    ErrorRecord[] array = new ErrorRecord[powerShell.Streams.Error.Count];
                                    powerShell.Streams.Error.CopyTo(array, 0);
                                    results = new PowerShellResults(output, new Collection <ErrorRecord>(array));
                                }
                                catch (RuntimeException ex)
                                {
                                    ErrorRecord errorRecord3;
                                    if (ex.ErrorRecord != null && !(ex is ParameterBindingException))
                                    {
                                        errorRecord3 = ex.ErrorRecord;
                                    }
                                    else
                                    {
                                        errorRecord3 = new ErrorRecord(ex, string.Empty, ErrorCategory.NotSpecified, null);
                                    }
                                    results = new PowerShellResults(new Collection <ErrorRecord>(new ErrorRecord[]
                                    {
                                        errorRecord3
                                    }));
                                }
                            }
                        });
                    }
                    catch (OverBudgetException exception)
                    {
                        ErrorRecord errorRecord = new ErrorRecord(exception, string.Empty, ErrorCategory.NotSpecified, null);
                        results = new PowerShellResults(new Collection <ErrorRecord>(new ErrorRecord[]
                        {
                            errorRecord
                        }));
                    }
                    catch (ADTransientException exception2)
                    {
                        ErrorRecord errorRecord2 = new ErrorRecord(exception2, string.Empty, ErrorCategory.NotSpecified, null);
                        results = new PowerShellResults(new Collection <ErrorRecord>(new ErrorRecord[]
                        {
                            errorRecord2
                        }));
                    }
                }
            });
            return(results);
        }
コード例 #10
0
        // Token: 0x06000018 RID: 24 RVA: 0x0000252C File Offset: 0x0000072C
        internal static Collection <PSObject> ExecuteCommandsInRunspace(SmtpAddress user, PSCommand command, CultureInfo executingCulture, out string errorMessage, out string warningMessage)
        {
            Collection <PSObject> result         = null;
            StringBuilder         stringBuilder  = new StringBuilder();
            StringBuilder         stringBuilder2 = new StringBuilder();

            errorMessage   = string.Empty;
            warningMessage = string.Empty;
            IRecipientSession recipientSession = ApprovalProcessor.CreateRecipientSessionFromSmtpAddress(user);
            ADUser            aduser           = recipientSession.FindByProxyAddress(ProxyAddress.Parse((string)user)) as ADUser;

            if (aduser == null)
            {
                errorMessage = Strings.ErrorUserNotFound((string)user);
                return(null);
            }
            GenericIdentity     identity            = new GenericIdentity(aduser.Sid.ToString());
            InitialSessionState initialSessionState = null;

            try
            {
                initialSessionState = new ExchangeRunspaceConfiguration(identity).CreateInitialSessionState();
                initialSessionState.LanguageMode = PSLanguageMode.FullLanguage;
            }
            catch (CmdletAccessDeniedException)
            {
                errorMessage = Strings.ErrorNoRBACRoleAssignment((string)user);
                return(null);
            }
            CultureInfo currentCulture   = Thread.CurrentThread.CurrentCulture;
            CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;

            try
            {
                if (executingCulture != null)
                {
                    Thread.CurrentThread.CurrentCulture   = executingCulture;
                    Thread.CurrentThread.CurrentUICulture = executingCulture;
                }
                using (RunspaceProxy runspaceProxy = new RunspaceProxy(new RunspaceMediator(new ForestScopeRunspaceFactory(new BasicInitialSessionStateFactory(initialSessionState), new BasicPSHostFactory(typeof(RunspaceHost), true)), new EmptyRunspaceCache())))
                {
                    try
                    {
                        PowerShellProxy powerShellProxy = new PowerShellProxy(runspaceProxy, command);
                        result = powerShellProxy.Invoke <PSObject>();
                        if (powerShellProxy.Errors != null)
                        {
                            foreach (ErrorRecord errorRecord in powerShellProxy.Errors)
                            {
                                stringBuilder.Append(errorRecord.ToString());
                            }
                        }
                        if (powerShellProxy.Warnings != null)
                        {
                            foreach (WarningRecord warningRecord in powerShellProxy.Warnings)
                            {
                                stringBuilder2.Append(warningRecord.ToString());
                            }
                        }
                    }
                    catch (CmdletInvocationException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    catch (ParameterBindingException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    catch (CommandNotFoundException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    catch (RuntimeException)
                    {
                        stringBuilder.Append(Strings.ErrorTaskInvocationFailed((string)user).ToString(executingCulture));
                    }
                    finally
                    {
                        errorMessage   = stringBuilder.ToString();
                        warningMessage = stringBuilder2.ToString();
                    }
                }
            }
            finally
            {
                if (executingCulture != null)
                {
                    Thread.CurrentThread.CurrentCulture   = currentCulture;
                    Thread.CurrentThread.CurrentUICulture = currentUICulture;
                }
            }
            return(result);
        }