Example #1
0
        protected override void ProcessRecord()
        {
            base.WriteVerbose(StringUtil.Format(RemotingErrorIdStrings.GcsScriptMessageV, "\r\nfunction ExtractPluginProperties([string]$pluginDir, $objectToWriteTo) \r\n{{\r\n    function Unescape-Xml($s) {{\r\n        if ($s) {{\r\n            $s = $s.Replace(\"&amp;\", \"&\");\r\n            $s = $s.Replace(\"&lt;\", \"<\");\r\n            $s = $s.Replace(\"&gt;\", \">\");\r\n            $s = $s.Replace(\"&quot;\", '\"');\r\n            $s = $s.Replace(\"&apos;\", \"'\");\r\n        }}        \r\n        return $s;\r\n    }}\r\n\r\n    $hashprovider = new-object system.collections.CaseInsensitiveHashCodeProvider\r\n    $comparer=new-object system.collections.CaseInsensitiveComparer\r\n    $h = new-object system.collections.hashtable([System.Collections.IHashCodeProvider]$hashprovider, [System.Collections.IComparer]$comparer)\r\n    \r\n    function Get-Details([string]$path, [hashtable]$h) {{\r\n        foreach ($o in (get-childitem -LiteralPath $path)) {{\r\n            if ($o.PSIsContainer) {{\r\n                Get-Details $o.PSPath $h\r\n            }} else {{\r\n                $h[$o.Name] = $o.Value\r\n            }}\r\n        }}\r\n    }}\r\n        \r\n    Get-Details $pluginDir $h\r\n        \r\n    if ($h[\"AssemblyName\"] -eq \"Microsoft.PowerShell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\") {{\r\n        \r\n        $serviceCore = [Reflection.Assembly]::Load(\"Microsoft.Powershell.Workflow.ServiceCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\")\r\n        \r\n        if ($serviceCore -ne $null) {{\r\n\r\n            $ci = new-Object system.management.automation.cmdletinfo \"New-PSWorkflowExecutionOptions\", ([Microsoft.PowerShell.Commands.NewPSWorkflowExecutionOptionCommand])\r\n            $wf = [powershell]::Create(\"currentrunspace\").AddCommand($ci).Invoke()\r\n    \r\n            if($wf -ne $null -and $wf.Count -ne 0) {{              \r\n                $wf = $wf[0]\r\n\r\n                foreach ($o in $wf.GetType().GetProperties()) {{\r\n                    $h[$o.Name] = $o.GetValue($wf, $null)\r\n                }}\r\n            }}\r\n        }}\r\n    }}\r\n\r\n    if (test-path -LiteralPath $pluginDir\\InitializationParameters\\SessionConfigurationData) {{\r\n        $xscd = [xml](Unescape-xml (get-item -LiteralPath $pluginDir\\InitializationParameters\\SessionConfigurationData).Value)\r\n\r\n        foreach ($o in $xscd.SessionConfigurationData.Param) {{\r\n            if ($o.Name -eq \"PrivateData\") {{\r\n                foreach($wf in $o.PrivateData.Param) {{\r\n                    $h[$wf.Name] = $wf.Value\r\n                }}\r\n            }} else {{\r\n                $h[$o.Name] = $o.Value\r\n            }}\r\n        }}\r\n    }}\r\n\r\n    ## Extract DISC related information\r\n    if(test-path -LiteralPath $pluginDir\\InitializationParameters\\ConfigFilePath) {{\r\n        $DISCFilePath = (get-item -LiteralPath $pluginDir\\InitializationParameters\\ConfigFilePath).Value\r\n\r\n        if(test-path -LiteralPath $DISCFilePath) {{\r\n            $DISCFileContent = get-content $DISCFilePath | out-string\r\n            $DISCHash = invoke-expression $DISCFileContent\r\n\r\n            foreach ($o in $DISCHash.Keys) {{   \r\n                if ($o -ne \"PowerShellVersion\") {{\r\n                    $objectToWriteTo = $objectToWriteTo | add-member -membertype noteproperty -name $o -value $DISCHash[$o] -force -passthru\r\n                }}\r\n            }}\r\n        }}\r\n    }}\r\n\r\n    if ($h[\"SessionConfigurationData\"]) {{\r\n        $h[\"SessionConfigurationData\"] = Unescape-Xml $h[\"SessionConfigurationData\"]\r\n    }}\r\n\r\n    foreach ($o in $h.Keys) {{\r\n        if ($o -eq 'sddl') {{\r\n            $objectToWriteTo = $objectToWriteTo | add-member -membertype noteproperty -name 'SecurityDescriptorSddl' -value $h[$o] -force -passthru\r\n        }} else {{\r\n            $objectToWriteTo = $objectToWriteTo | add-member -membertype noteproperty -name $o -value $h[$o] -force -passthru\r\n        }}\r\n    }}\r\n}}\r\n\r\n$shellNotErrMsgFormat = $args[1]\r\n$args[0] | foreach {{\r\n  $shellsFound = 0;\r\n  $filter = $_\r\n  dir 'WSMan:\\localhost\\Plugin\\' | ? {{ $_.name -like \"$filter\" }} | foreach {{\r\n     $customPluginObject = new-object object     \r\n     $customPluginObject.pstypenames.Insert(0, '{0}')\r\n     ExtractPluginProperties \"$($_.PSPath)\" $customPluginObject\r\n     # this is powershell based custom shell only if its plugin dll is pwrshplugin.dll\r\n     if (($customPluginObject.FileName) -and ($customPluginObject.FileName -match '{1}'))\r\n     {{\r\n        $shellsFound++\r\n        $customPluginObject\r\n     }}\r\n    }} # end of foreach\r\n   \r\n    if (!$shellsFound -and !([System.Management.Automation.WildcardPattern]::ContainsWildcardCharacters($_)))\r\n    {{\r\n      $errMsg = $shellNotErrMsgFormat -f $_\r\n      Write-Error $errMsg \r\n    }}     \r\n  }}\r\n"));
            string customShellNotFound = RemotingErrorIdStrings.CustomShellNotFound;
            object shellName           = "*";

            if (this.shellName != null)
            {
                shellName = this.shellName;
            }
            ActionPreference errorActionPreferenceVariable = base.Context.ErrorActionPreferenceVariable;

            try
            {
                if (base.Context.CurrentCommandProcessor.CommandRuntime.IsErrorActionSet)
                {
                    base.Context.ErrorActionPreferenceVariable = base.Context.CurrentCommandProcessor.CommandRuntime.ErrorAction;
                }
                getPluginSb.InvokeUsingCmdlet(this, true, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, AutomationNull.Value, new object[0], AutomationNull.Value, new object[] { shellName, customShellNotFound });
            }
            finally
            {
                base.Context.ErrorActionPreferenceVariable = errorActionPreferenceVariable;
            }
        }
        private Exception HandleException(
            Token statementToken,
            RuntimeException rte,
            Pipe outputPipe,
            ref ArrayList resultList,
            ExecutionContext context)
        {
            this.SetErrorVariables(statementToken, rte, context, outputPipe);
            context.QuestionMarkVariableValue = false;
            if (this._traps == null && !this.NeedToQueryForActionPreference(rte, context))
            {
                return((Exception)rte);
            }
            ActionPreference actionPreference = this._traps == null?this.QueryForAction(rte, rte.Message, context) : this.ProcessTraps(rte, outputPipe, ref resultList, context);

            context.QuestionMarkVariableValue = false;
            if (actionPreference == ActionPreference.SilentlyContinue)
            {
                return((Exception)null);
            }
            if (actionPreference == ActionPreference.Stop)
            {
                rte.SuppressPromptInInterpreter = true;
                return((Exception)rte);
            }
            if (this._traps == null && rte.WasThrownFromThrowStatement)
            {
                return((Exception)rte);
            }
            bool flag = this.ReportErrorRecord(statementToken, rte, context);

            context.QuestionMarkVariableValue = false;
            return(!flag ? (Exception)rte : (Exception)null);
        }
Example #3
0
        private static void WarnAboutUnsupportedActionPreferences(
            Cmdlet cmdlet,
            ActionPreference effectiveActionPreference,
            string nameOfCommandLineParameter,
            Func <string> inquireMessageGetter,
            Func <string> stopMessageGetter)
        {
            string message;

            switch (effectiveActionPreference)
            {
            case ActionPreference.Stop:
                message = stopMessageGetter();
                break;

            case ActionPreference.Inquire:
                message = inquireMessageGetter();
                break;

            default:
                return;     // we can handle everything that is not Stop or Inquire
            }

            bool actionPreferenceComesFromCommandLineParameter = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter);

            if (actionPreferenceComesFromCommandLineParameter)
            {
                Exception   exception   = new ArgumentException(message);
                ErrorRecord errorRecord = new ErrorRecord(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null);
                cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
Example #4
0
        private CimResponseType WriteErrorCallback(CimInstance cimError)
        {
            lock (this._jobStateLock)
            {
                this._jobHadErrors = true;
            }
            CimException     cimException          = new CimException(cimError);
            CimJobException  cimJobException       = CimJobException.CreateFromCimException(this.GetDescription(), this.JobContext, cimException);
            ErrorRecord      errorRecord           = cimJobException.ErrorRecord;
            ActionPreference errorActionPreference = this.JobContext.ErrorActionPreference;

            switch (errorActionPreference)
            {
            case ActionPreference.Stop:
            case ActionPreference.Inquire:
            {
                return(this.BlockingWriteError(errorRecord));
            }

            case ActionPreference.Continue:
            {
                this.WriteError(errorRecord);
                return(CimResponseType.Yes);
            }

            default:
            {
                this.WriteError(errorRecord);
                return(CimResponseType.Yes);
            }
            }
        }
Example #5
0
        internal void WriteDebugLine(string message, ref ActionPreference preference)
        {
            using (InternalHostUserInterface.tracer.TraceMethod(message, new object[0]))
            {
                InternalHostUserInterface.tracer.WriteLine((object)preference);
                switch (preference)
                {
                case ActionPreference.SilentlyContinue:
                    break;

                case ActionPreference.Stop:
                    this.WriteDebugLineHelper(message);
                    ActionPreferenceStopException preferenceStopException1 = new ActionPreferenceStopException(new ErrorRecord((Exception) new ParentContainsErrorRecordException(ResourceManagerCache.GetResourceString("InternalHostUserInterfaceStrings", "WriteDebugLineStoppedError")), "ActionPreferenceStop", ErrorCategory.OperationStopped, (object)null));
                    InternalHostUserInterface.tracer.TraceException((Exception)preferenceStopException1);
                    throw preferenceStopException1;

                case ActionPreference.Continue:
                    this.WriteDebugLineHelper(message);
                    break;

                case ActionPreference.Inquire:
                    if (!this.DebugShouldContinue(message, ref preference))
                    {
                        ActionPreferenceStopException preferenceStopException2 = new ActionPreferenceStopException(new ErrorRecord((Exception) new ParentContainsErrorRecordException(ResourceManagerCache.GetResourceString("InternalHostUserInterfaceStrings", "WriteDebugLineStoppedError")), "UserStopRequest", ErrorCategory.OperationStopped, (object)null));
                        InternalHostUserInterface.tracer.TraceException((Exception)preferenceStopException2);
                        throw preferenceStopException2;
                    }
                    this.WriteDebugLineHelper(message);
                    break;

                default:
                    throw InternalHostUserInterface.tracer.NewArgumentException(nameof(preference), "InternalHostUserInterfaceStrings", "UnsupportedPreferenceError", (object)preference);
                }
            }
        }
        public Collection <PSObject> Execute()
        {
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript($"cd \"{this.root}\"\n");
                PowerShellInstance.AddScript(this.GetScript());
                Collection <PSObject> result = PowerShellInstance.Invoke();

                if (PowerShellInstance.Streams.Error.Count > 0)
                {
                    foreach (ErrorRecord error in PowerShellInstance.Streams.Error)
                    {
                        PSCmdlet target = error.TargetObject as PSCmdlet;
                        if (target != null)
                        {
                            ActionPreference param = (ActionPreference)target.MyInvocation.BoundParameters["ErrorAction"];
                            if (param == ActionPreference.Continue)
                            {
                                continue;
                            }

                            throw new AggregateException($"Failed to execute script.\n{error.ToString()}");
                        }

                        if (error.FullyQualifiedErrorId.Equals("CommandNotFoundException",
                                                               StringComparison.InvariantCultureIgnoreCase))
                        {
                            throw new CommandNotFoundException(error.Exception.Message);
                        }
                    }
                }

                return(result);
            }
        }
        private static void WarnAboutUnsupportedActionPreferences(
            Cmdlet cmdlet,
            ActionPreference effectiveActionPreference,
            string nameOfCommandLineParameter,
            Func<string> inquireMessageGetter,
            Func<string> stopMessageGetter)
        {
            string message;
            switch (effectiveActionPreference)
            {
                case ActionPreference.Stop:
                    message = stopMessageGetter();
                    break;

                case ActionPreference.Inquire:
                    message = inquireMessageGetter();
                    break;

                default:
                    return; // we can handle everything that is not Stop or Inquire
            }

            bool actionPreferenceComesFromCommandLineParameter = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter);
            if (actionPreferenceComesFromCommandLineParameter)
            {
                Exception exception = new ArgumentException(message);
                ErrorRecord errorRecord = new ErrorRecord(exception, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null);
                cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
        internal void WriteDebugLine(string message, ref ActionPreference preference)
        {
            ErrorRecord error = null;

            switch (preference)
            {
            case ActionPreference.SilentlyContinue:
            case ActionPreference.Ignore:
                return;

            case ActionPreference.Stop:
            {
                this.WriteDebugLineHelper(message);
                error = new ErrorRecord(new ParentContainsErrorRecordException(InternalHostUserInterfaceStrings.WriteDebugLineStoppedError), "ActionPreferenceStop", ErrorCategory.OperationStopped, null);
                ActionPreferenceStopException exception2 = new ActionPreferenceStopException(error);
                throw exception2;
            }

            case ActionPreference.Continue:
                this.WriteDebugLineHelper(message);
                return;

            case ActionPreference.Inquire:
                if (!this.DebugShouldContinue(message, ref preference))
                {
                    error = new ErrorRecord(new ParentContainsErrorRecordException(InternalHostUserInterfaceStrings.WriteDebugLineStoppedError), "UserStopRequest", ErrorCategory.OperationStopped, null);
                    ActionPreferenceStopException exception = new ActionPreferenceStopException(error);
                    throw exception;
                }
                this.WriteDebugLineHelper(message);
                return;
            }
            throw PSTraceSource.NewArgumentException("preference", "InternalHostUserInterfaceStrings", "UnsupportedPreferenceError", new object[] { (ActionPreference)preference });
        }
        DebugShouldContinue(string message, ref ActionPreference actionPreference)
        {
            Dbg.Assert(actionPreference == ActionPreference.Inquire, "Why are you inquiring if your preference is not to?");

            bool shouldContinue = false;

            Collection <ChoiceDescription> choices = new Collection <ChoiceDescription>();

            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesLabel, InternalHostUserInterfaceStrings.ShouldContinueYesHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueYesToAllHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoLabel, InternalHostUserInterfaceStrings.ShouldContinueNoHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueNoToAllHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueSuspendLabel, InternalHostUserInterfaceStrings.ShouldContinueSuspendHelp));

            bool endLoop = true;

            do
            {
                endLoop = true;

                switch (
                    PromptForChoice(
                        InternalHostUserInterfaceStrings.ShouldContinuePromptMessage,
                        message,
                        choices,
                        0))
                {
                case 0:
                    shouldContinue = true;
                    break;

                case 1:
                    actionPreference = ActionPreference.Continue;
                    shouldContinue   = true;
                    break;

                case 2:
                    shouldContinue = false;
                    break;

                case 3:
                    // No to All means that we want to stop everytime WriteDebug is called. Since No throws an error, I
                    // think that ordinarily, the caller will terminate.  So I don't think the caller will ever get back
                    // calling WriteDebug again, and thus "No to All" might not be a useful option to have.

                    actionPreference = ActionPreference.Stop;
                    shouldContinue   = false;
                    break;

                case 4:
                    // This call returns when the user exits the nested prompt.

                    _parent.EnterNestedPrompt();
                    endLoop = false;
                    break;
                }
            } while (endLoop != true);

            return(shouldContinue);
        }
        internal CimCmdletInvocationContext(CimCmdletDefinitionContext cmdletDefinitionContext, Cmdlet cmdlet, string namespaceOverride)
        {
            this._defaultCimSession      = new Lazy <CimSession>(new Func <CimSession>(CimCmdletInvocationContext.CreateDefaultCimSession));
            this.CmdletDefinitionContext = cmdletDefinitionContext;
            this.NamespaceOverride       = namespaceOverride;
            this.CmdletInvocationInfo    = cmdlet.MyInvocation;
            MshCommandRuntime commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;

            this.DebugActionPreference = commandRuntime.DebugPreference;
            Cmdlet           cmdlet1 = cmdlet;
            ActionPreference debugActionPreference = this.DebugActionPreference;
            string           str  = "Debug";
            Func <string>    func = () => CmdletizationResources.CimCmdletAdapter_DebugInquire;

            CimCmdletInvocationContext.WarnAboutUnsupportedActionPreferences(cmdlet1, debugActionPreference, str, func, () => string.Empty);
            this.WarningActionPreference = commandRuntime.WarningPreference;
            Cmdlet           cmdlet2 = cmdlet;
            ActionPreference warningActionPreference = this.WarningActionPreference;
            string           str1  = "WarningAction";
            Func <string>    func1 = () => CmdletizationResources.CimCmdletAdapter_WarningInquire;

            CimCmdletInvocationContext.WarnAboutUnsupportedActionPreferences(cmdlet2, warningActionPreference, str1, func1, () => CmdletizationResources.CimCmdletAdapter_WarningStop);
            this.VerboseActionPreference   = commandRuntime.VerbosePreference;
            this.ErrorActionPreference     = commandRuntime.ErrorAction;
            this.ShouldProcessOptimization = commandRuntime.CalculatePossibleShouldProcessOptimization();
        }
        private static void WarnAboutUnsupportedActionPreferences(Cmdlet cmdlet, ActionPreference effectiveActionPreference, string nameOfCommandLineParameter, Func <string> inquireMessageGetter, Func <string> stopMessageGetter)
        {
            string           str;
            ActionPreference actionPreference = effectiveActionPreference;

            if (actionPreference == ActionPreference.Stop)
            {
                str = stopMessageGetter();
            }
            else if (actionPreference == ActionPreference.Continue)
            {
                return;
            }
            else if (actionPreference == ActionPreference.Inquire)
            {
                str = inquireMessageGetter();
            }
            else
            {
                return;
            }
            bool flag = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter);

            if (flag)
            {
                Exception   argumentException = new ArgumentException(str);
                ErrorRecord errorRecord       = new ErrorRecord(argumentException, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null);
                cmdlet.ThrowTerminatingError(errorRecord);
            }
        }
Example #12
0
        private ActionPreference QueryForAction(
            RuntimeException rte,
            string message,
            ExecutionContext context)
        {
            ActionPreference enumPreference = context.GetEnumPreference <ActionPreference>(InitialSessionState.errorActionPreferenceVariablePath, ActionPreference.Continue, out bool _);

            return(enumPreference != ActionPreference.Inquire || rte.SuppressPromptInInterpreter ? enumPreference : this.InquireForActionPreference(message, context));
        }
        public void WriteError(ErrorRecord errorRecord)
        {
            ActionPreference value;

            if (this.Error != null)
            {
                ErrorRecord      errorRecord1 = new ErrorRecord(errorRecord.Exception, string.Concat(errorRecord.FullyQualifiedErrorId, (char)44, this._cmdletType.FullName), errorRecord.CategoryInfo.Category, errorRecord.TargetObject);
                ActionPreference?errorAction  = this._implementationContext.ErrorAction;
                if (!errorAction.HasValue)
                {
                    value = ActionPreference.Continue;
                }
                else
                {
                    ActionPreference?nullable = this._implementationContext.ErrorAction;
                    value = nullable.Value;
                }
                ActionPreference actionPreference  = value;
                ActionPreference actionPreference1 = actionPreference;
                switch (actionPreference1)
                {
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Ignore:
                {
                    return;
                }

                case ActionPreference.Stop:
                {
                    this.ThrowTerminatingError(errorRecord1);
                    return;
                }

                case ActionPreference.Continue:
                case ActionPreference.Inquire:
                {
                    if (errorRecord == null)
                    {
                        return;
                    }
                    this.Error.Add(errorRecord1);
                    return;
                }

                default:
                {
                    return;
                }
                }
            }
            else
            {
                return;
            }
        }
Example #14
0
        internal static ActionPreference QueryForAction(RuntimeException rte, string message, ExecutionContext context)
        {
            bool             flag;
            ActionPreference preference = context.GetEnumPreference <ActionPreference>(SpecialVariables.ErrorActionPreferenceVarPath, ActionPreference.Continue, out flag);

            if ((preference == ActionPreference.Inquire) && !rte.SuppressPromptInInterpreter)
            {
                return(InquireForActionPreference(message, context));
            }
            return(preference);
        }
Example #15
0
        internal void TraceLine(IScriptExtent extent)
        {
            string message = PositionUtilities.BriefMessage(extent.StartScriptPosition);
            InternalHostUserInterface uI         = (InternalHostUserInterface)this._context.EngineHostInterface.UI;
            ActionPreference          preference = this._context.PSDebugTraceStep ? ActionPreference.Inquire : ActionPreference.Continue;

            uI.WriteDebugLine(message, ref preference);
            if (preference == ActionPreference.Continue)
            {
                this._context.PSDebugTraceStep = false;
            }
        }
        WriteDebugLine(string message, ref ActionPreference preference)
        {
            string      errorMsg    = null;
            ErrorRecord errorRecord = null;

            switch (preference)
            {
            case ActionPreference.Continue:
            case ActionPreference.Break:
                WriteDebugLineHelper(message);
                break;

            case ActionPreference.SilentlyContinue:
            case ActionPreference.Ignore:
                break;

            case ActionPreference.Inquire:
                if (!DebugShouldContinue(message, ref preference))
                {
                    // user asked to exit with an error

                    errorMsg    = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
                    errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
                                                  "UserStopRequest", ErrorCategory.OperationStopped, null);
                    ActionPreferenceStopException e = new ActionPreferenceStopException(errorRecord);
                    // We cannot call ThrowTerminatingError since this is not a cmdlet or provider
                    throw e;
                }
                else
                {
                    WriteDebugLineHelper(message);
                }

                break;

            case ActionPreference.Stop:
                WriteDebugLineHelper(message);

                errorMsg    = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
                errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
                                              "ActionPreferenceStop", ErrorCategory.OperationStopped, null);
                ActionPreferenceStopException ense = new ActionPreferenceStopException(errorRecord);
                // We cannot call ThrowTerminatingError since this is not a cmdlet or provider
                throw ense;

            default:
                Dbg.Assert(false, "all preferences should be checked");
                throw PSTraceSource.NewArgumentException(nameof(preference),
                                                         InternalHostUserInterfaceStrings.UnsupportedPreferenceError, preference);
                // break;
            }
        }
Example #17
0
        internal T GetEnumPreference <T>(VariablePath preferenceVariablePath, T defaultPref, out bool defaultUsed)
        {
            CmdletProviderContext context = null;
            SessionStateScope     scope   = null;
            object obj2 = this.EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope);

            if (obj2 is T)
            {
                if (obj2 is ActionPreference)
                {
                    ActionPreference o = (ActionPreference)obj2;
                    if (o == ActionPreference.Ignore)
                    {
                        this.EngineSessionState.SetVariableValue(preferenceVariablePath.UserPath, defaultPref);
                        throw new NotSupportedException(StringUtil.Format(ErrorPackage.UnsupportedPreferenceError, o));
                    }
                }
                T local = (T)obj2;
                defaultUsed = false;
                return(local);
            }
            defaultUsed = true;
            T local2 = defaultPref;

            if (obj2 != null)
            {
                try
                {
                    string str2 = obj2 as string;
                    if (str2 != null)
                    {
                        local2      = (T)Enum.Parse(typeof(T), str2, true);
                        defaultUsed = false;
                        return(local2);
                    }
                    local2      = (T)obj2;
                    defaultUsed = false;
                }
                catch (InvalidCastException)
                {
                }
                catch (ArgumentException)
                {
                }
            }
            return(local2);
        }
Example #18
0
        internal static void TraceLine(ExecutionContext context, ParseTreeNode statement)
        {
            if (statement == null || !context.ShouldTraceStatement || statement.NodeToken == null)
            {
                return;
            }
            string message = statement.NodeToken.Position(false);
            InternalHostUserInterface ui         = (InternalHostUserInterface)context.EngineHostInterface.UI;
            ActionPreference          preference = context.StepScript ? ActionPreference.Inquire : ActionPreference.Continue;

            ui.WriteDebugLine(message, ref preference);
            if (preference != ActionPreference.Continue)
            {
                return;
            }
            context.StepScript = false;
        }
Example #19
0
        public override string Run()
        {
            StringBuilder results = new StringBuilder();

            State = TaskState.Running;
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript(GetScript());
                try
                {
                    PowerShellInstance.Invoke();
                }
                catch (Exception)
                {
                    State = TaskState.Failed;
                    throw;
                }

                if (PowerShellInstance.Streams.Error.Count > 0)
                {
                    foreach (ErrorRecord error in PowerShellInstance.Streams.Error)
                    {
                        PSCmdlet target = error.TargetObject as PSCmdlet;
                        if (target != null)
                        {
                            ActionPreference param = (ActionPreference)target.MyInvocation.BoundParameters["ErrorAction"];
                            if (param == ActionPreference.Continue)
                            {
                                continue;
                            }
                        }

                        results.AppendLine(error.ToString());
                    }

                    State = results.Length > 0 ? TaskState.Warning : TaskState.Finished;
                }
                else
                {
                    State = TaskState.Finished;
                }
            }

            return(results.ToString());
        }
Example #20
0
        private bool DebugShouldContinue(string message, ref ActionPreference actionPreference)
        {
            using (InternalHostUserInterface.tracer.TraceMethod(message, new object[0]))
            {
                InternalHostUserInterface.tracer.WriteLine((object)actionPreference);
                bool flag1 = false;
                Collection <ChoiceDescription> choices = new Collection <ChoiceDescription>();
                choices.Add(new ChoiceDescription("InternalHostUserInterfaceStrings", "ShouldContinueYesLabel", "ShouldContinueYesHelp"));
                choices.Add(new ChoiceDescription("InternalHostUserInterfaceStrings", "ShouldContinueYesToAllLabel", "ShouldContinueYesToAllHelp"));
                choices.Add(new ChoiceDescription("InternalHostUserInterfaceStrings", "ShouldContinueNoLabel", "ShouldContinueNoHelp"));
                choices.Add(new ChoiceDescription("InternalHostUserInterfaceStrings", "ShouldContinueNoToAllLabel", "ShouldContinueNoToAllHelp"));
                choices.Add(new ChoiceDescription("InternalHostUserInterfaceStrings", "ShouldContinueSuspendLabel", "ShouldContinueSuspendHelp"));
                bool flag2;
                do
                {
                    flag2 = true;
                    switch (this.PromptForChoice(ResourceManagerCache.GetResourceString("InternalHostUserInterfaceStrings", "ShouldContinuePromptMessage"), message, choices, 0))
                    {
                    case 0:
                        flag1 = true;
                        break;

                    case 1:
                        actionPreference = ActionPreference.Continue;
                        flag1            = true;
                        break;

                    case 2:
                        flag1 = false;
                        break;

                    case 3:
                        actionPreference = ActionPreference.Stop;
                        flag1            = false;
                        break;

                    case 4:
                        this.parent.EnterNestedPrompt();
                        flag2 = false;
                        break;
                    }
                }while (!flag2);
                return(flag1);
            }
        }
Example #21
0
        internal void Trace(string messageId, string resourceString, params object[] args)
        {
            string           str;
            ActionPreference preference = ActionPreference.Continue;

            if ((args == null) || (args.Length == 0))
            {
                str = resourceString;
            }
            else
            {
                str = StringUtil.Format(resourceString, args);
            }
            if (string.IsNullOrEmpty(str))
            {
                str = "Could not load text for msh script tracing message id '" + messageId + "'";
            }
            ((InternalHostUserInterface)this._context.EngineHostInterface.UI).WriteDebugLine(str, ref preference);
        }
        private bool DebugShouldContinue(string message, ref ActionPreference actionPreference)
        {
            bool flag = false;
            Collection<ChoiceDescription> choices = new Collection<ChoiceDescription> {
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesLabel, InternalHostUserInterfaceStrings.ShouldContinueYesHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueYesToAllHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoLabel, InternalHostUserInterfaceStrings.ShouldContinueNoHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueNoToAllHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueSuspendLabel, InternalHostUserInterfaceStrings.ShouldContinueSuspendHelp)
            };
            bool flag2 = true;
            do
            {
                flag2 = true;
                switch (this.PromptForChoice(InternalHostUserInterfaceStrings.ShouldContinuePromptMessage, message, choices, 0))
                {
                    case 0:
                        flag = true;
                        break;

                    case 1:
                        actionPreference = ActionPreference.Continue;
                        flag = true;
                        break;

                    case 2:
                        flag = false;
                        break;

                    case 3:
                        actionPreference = ActionPreference.Stop;
                        flag = false;
                        break;

                    case 4:
                        this.parent.EnterNestedPrompt();
                        flag2 = false;
                        break;
                }
            }
            while (!flag2);
            return flag;
        }
        private bool DebugShouldContinue(string message, ref ActionPreference actionPreference)
        {
            bool flag = false;
            Collection <ChoiceDescription> choices = new Collection <ChoiceDescription> {
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesLabel, InternalHostUserInterfaceStrings.ShouldContinueYesHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueYesToAllHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoLabel, InternalHostUserInterfaceStrings.ShouldContinueNoHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueNoToAllHelp),
                new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueSuspendLabel, InternalHostUserInterfaceStrings.ShouldContinueSuspendHelp)
            };
            bool flag2 = true;

            do
            {
                flag2 = true;
                switch (this.PromptForChoice(InternalHostUserInterfaceStrings.ShouldContinuePromptMessage, message, choices, 0))
                {
                case 0:
                    flag = true;
                    break;

                case 1:
                    actionPreference = ActionPreference.Continue;
                    flag             = true;
                    break;

                case 2:
                    flag = false;
                    break;

                case 3:
                    actionPreference = ActionPreference.Stop;
                    flag             = false;
                    break;

                case 4:
                    this.parent.EnterNestedPrompt();
                    flag2 = false;
                    break;
                }
            }while (!flag2);
            return(flag);
        }
Example #24
0
        internal static void Trace(
            ExecutionContext context,
            int level,
            string messageId,
            params object[] args)
        {
            ActionPreference preference = ActionPreference.Continue;

            if (context.PSDebug <= level)
            {
                return;
            }
            string message = args == null || args.Length == 0 ? ResourceManagerCache.GetResourceString("Parser", messageId) : ResourceManagerCache.FormatResourceString("Parser", messageId, args);

            if (string.IsNullOrEmpty(message))
            {
                message = "Could not load text for msh script tracing message id '" + messageId + "'";
            }
            ((InternalHostUserInterface)context.EngineHostInterface.UI).WriteDebugLine(message, ref preference);
        }
Example #25
0
 internal void WriteError(ErrorRecord errorRecord, bool overrideInquire)
 {
     this.ThrowIfStopping();
     ActionPreference errorAction = this.ErrorAction;
     if (overrideInquire && (errorAction == ActionPreference.Inquire))
     {
         errorAction = ActionPreference.Continue;
     }
     if (this.UseSecurityContextRun)
     {
         if ((this.pipelineProcessor == null) || (this.pipelineProcessor.SecurityContext == null))
         {
             throw PSTraceSource.NewInvalidOperationException("pipeline", "WriteNotPermitted", new object[0]);
         }
         ContextCallback callback = new ContextCallback(this.DoWriteError);
         SecurityContext.Run(this.pipelineProcessor.SecurityContext.CreateCopy(), callback, new KeyValuePair<ErrorRecord, ActionPreference>(errorRecord, errorAction));
     }
     else
     {
         this.DoWriteError(new KeyValuePair<ErrorRecord, ActionPreference>(errorRecord, errorAction));
     }
 }
Example #26
0
        /// <summary>
        /// Should the verbose/debug/progress message be printed?
        /// </summary>
        /// <param name="preference"></param>
        /// <param name="lastContinueStatus"></param>
        /// <returns></returns>
        /// <exception cref="System.Management.Automation.PipelineStoppedException"></exception>
        /// <exception cref="System.InvalidOperationException"></exception>
        internal bool WriteHelper_ShouldWrite(
            ActionPreference preference,
            ContinueStatus lastContinueStatus)
        {
            ThrowIfStopping();

            // 2005/05/24 908827
            // WriteDebug/WriteVerbose/WriteProgress/WriteWarning should only be callable from the main thread
            //
            // WriteError/WriteObject have a check that prevents them to be called from outside 
            // Begin/Process/End. This is done because the Pipeline needs to be ready before these 
            // functions can be called.
            //
            // WriteDebug/Warning/Verbose/Process used to do the same check, even though it is not 
            // strictly needed. If we ever implement pipelines for these objects we may need to 
            // enforce the check again.
            //
            // See bug 583774 in the Windows 7 database for more details.
            //
            ThrowIfWriteNotPermitted(false);

            switch (lastContinueStatus)
            {
                case ContinueStatus.NoToAll:  // previously answered NoToAll
                    return false;
                case ContinueStatus.YesToAll: // previously answered YesToAll
                    return true;
            }

            switch (preference)
            {
                case ActionPreference.Ignore:
                case ActionPreference.SilentlyContinue:
                    return false;

                case ActionPreference.Continue:
                case ActionPreference.Stop:
                case ActionPreference.Inquire:
                    return true;

                default:
                    Dbg.Assert(false, "Bad preference value" + preference);
                    return true;
            }
        } // WriteHelper_ShouldWrite
Example #27
0
        } // WriteHelper_ShouldWrite

        /// <summary>
        /// Complete implementation of WriteDebug/WriteVerbose/WriteProgress
        /// </summary>
        /// <param name="inquireCaption"></param>
        /// <param name="inquireMessage"></param>
        /// <param name="preference"></param>
        /// <param name="lastContinueStatus"></param>
        /// <param name="preferenceVariableName"></param>
        /// <param name="message"></param>
        /// <returns>Did Inquire return YesToAll?</returns>
        /// <exception cref="System.Management.Automation.PipelineStoppedException">
        /// The pipeline has already been terminated, or was terminated
        /// during the execution of this method.
        /// The Cmdlet should generally just allow PipelineStoppedException
        /// to percolate up to the caller of ProcessRecord etc.
        /// </exception>
        /// <remarks>
        /// If the pipeline is terminated due to ActionPreference.Stop
        /// or ActionPreference.Inquire, this method will throw
        /// <see cref="System.Management.Automation.PipelineStoppedException"/>,
        /// but the command failure will ultimately be
        /// <see cref="System.Management.Automation.ActionPreferenceStopException"/>,
        /// </remarks>
        internal ContinueStatus WriteHelper(
            string inquireCaption,
            string inquireMessage,
            ActionPreference preference,
            ContinueStatus lastContinueStatus,
            string preferenceVariableName,
            string message)
        {
            switch (lastContinueStatus)
            {
                case ContinueStatus.NoToAll:  // previously answered NoToAll
                    return ContinueStatus.NoToAll;
                case ContinueStatus.YesToAll: // previously answered YesToAll
                    return ContinueStatus.YesToAll;
            }

            switch (preference)
            {
                case ActionPreference.Ignore: // YesToAll
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Continue:
                    return ContinueStatus.Yes;

                case ActionPreference.Stop:
                    ActionPreferenceStopException e =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            StringUtil.Format(CommandBaseStrings.ErrorPreferenceStop, preferenceVariableName, message));
                    throw ManageException(e);

                case ActionPreference.Inquire:
                    break;

                default:
                    Dbg.Assert(false, "Bad preference value" + preference);
                    ActionPreferenceStopException apse =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            StringUtil.Format(CommandBaseStrings.PreferenceInvalid, preferenceVariableName, preference));
                    throw ManageException(apse);
            }

            return InquireHelper(
                inquireMessage,
                inquireCaption,
                true,  // allowYesToAll
                false, // allowNoToAll
                true,  // replaceNoWithHalt
                false  // hasSecurityImpact
            );
        } // WriteHelper
        internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, bool bindingParameters, bool bindingScriptCmdlet)
        {
            if (_convertTypes == null)
            {
                return(inputData);
            }

            object result = inputData;

            try
            {
                for (int i = 0; i < _convertTypes.Length; i++)
                {
                    if (bindingParameters)
                    {
                        // We should not be doing a conversion here if [ref] is the last type.
                        // When [ref] appears in an argument list, it is used for checking only.
                        // No Conversion should be done.
                        if (_convertTypes[i].Equals(typeof(System.Management.Automation.PSReference)))
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            PSReference reference = temp as PSReference;

                            if (reference == null)
                            {
                                throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null,
                                                                 ExtendedTypeSystem.ReferenceTypeExpected);
                            }
                        }
                        else
                        {
                            object   temp;
                            PSObject mshObject = result as PSObject;
                            if (mshObject != null)
                            {
                                temp = mshObject.BaseObject;
                            }
                            else
                            {
                                temp = result;
                            }

                            // If a non-ref type is expected but currently passed in is a ref, do an implicit dereference.
                            PSReference reference = temp as PSReference;

                            if (reference != null)
                            {
                                result = reference.Value;
                            }

                            if (bindingScriptCmdlet && _convertTypes[i] == typeof(string))
                            {
                                // Don't allow conversion from array to string in script w/ cmdlet binding.  Allow
                                // the conversion for ordinary script parameter binding for V1 compatibility.
                                temp = PSObject.Base(result);
                                if (temp != null && temp.GetType().IsArray)
                                {
                                    throw new PSInvalidCastException("InvalidCastFromAnyTypeToString", null,
                                                                     ExtendedTypeSystem.InvalidCastCannotRetrieveString);
                                }
                            }
                        }
                    }

                    //BUGBUG
                    //NTRAID#Windows Out of Band Releases - 930116 - 03/14/06
                    //handling special case for boolean, switchparameter and Nullable<bool>
                    //These parameter types will not be converted if the incoming value types are not
                    //one of the accepted categories - $true/$false or numbers (0 or otherwise)
                    if (LanguagePrimitives.IsBoolOrSwitchParameterType(_convertTypes[i]))
                    {
                        CheckBoolValue(result, _convertTypes[i]);
                    }

                    if (bindingScriptCmdlet)
                    {
                        // Check for conversion to something like bool[] or ICollection<bool>, but only for cmdlet binding
                        // to stay compatible with V1.
                        ParameterCollectionTypeInformation collectionTypeInfo = new ParameterCollectionTypeInformation(_convertTypes[i]);
                        if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection &&
                            LanguagePrimitives.IsBoolOrSwitchParameterType(collectionTypeInfo.ElementType))
                        {
                            IList currentValueAsIList = ParameterBinderBase.GetIList(result);
                            if (currentValueAsIList != null)
                            {
                                foreach (object val in currentValueAsIList)
                                {
                                    CheckBoolValue(val, collectionTypeInfo.ElementType);
                                }
                            }
                            else
                            {
                                CheckBoolValue(result, collectionTypeInfo.ElementType);
                            }
                        }
                    }

                    result = LanguagePrimitives.ConvertTo(result, _convertTypes[i], CultureInfo.InvariantCulture);

                    // Do validation of invalid direct variable assignments which are allowed to
                    // be used for parameters.
                    //
                    // Note - this is duplicated in ExecutionContext.cs as parameter binding for script cmdlets can avoid this code path.
                    if ((!bindingScriptCmdlet) && (!bindingParameters))
                    {
                        // ActionPreference of Suspend is not supported as a preference variable. We can only block "Suspend"
                        // during variable assignment (here) - "Ignore" is blocked during variable retrieval.
                        if (_convertTypes[i] == typeof(ActionPreference))
                        {
                            ActionPreference resultPreference = (ActionPreference)result;

                            if (resultPreference == ActionPreference.Suspend)
                            {
                                throw new PSInvalidCastException("InvalidActionPreference", null, ErrorPackage.UnsupportedPreferenceVariable, resultPreference);
                            }
                        }
                    }
                }
            }
            catch (PSInvalidCastException e)
            {
                throw new ArgumentTransformationMetadataException(e.Message, e);
            }

            return(result);
        }
Example #29
0
 internal void WriteDebug(DebugRecord record, bool overrideInquire = false)
 {
     ActionPreference debugPreference = this.DebugPreference;
     if (overrideInquire && (debugPreference == ActionPreference.Inquire))
     {
         debugPreference = ActionPreference.Continue;
     }
     if (this.WriteHelper_ShouldWrite(debugPreference, this.lastDebugContinueStatus))
     {
         if (record.InvocationInfo == null)
         {
             record.SetInvocationInfo(this.MyInvocation);
         }
         if (this.DebugOutputPipe != null)
         {
             if (((this.CBhost != null) && (this.CBhost.InternalUI != null)) && this.DebugOutputPipe.NullPipe)
             {
                 this.CBhost.InternalUI.WriteDebugInfoBuffers(record);
             }
             PSObject obj2 = PSObject.AsPSObject(record);
             if (obj2.Members["WriteDebugStream"] == null)
             {
                 obj2.Properties.Add(new PSNoteProperty("WriteDebugStream", true));
             }
             this.DebugOutputPipe.Add(obj2);
         }
         else
         {
             if ((this.Host == null) || (this.Host.UI == null))
             {
                 throw PSTraceSource.NewInvalidOperationException();
             }
             this.CBhost.InternalUI.WriteDebugRecord(record);
         }
     }
     this.lastDebugContinueStatus = this.WriteHelper(null, null, debugPreference, this.lastDebugContinueStatus, "DebugPreference", record.Message);
 }
Example #30
0
        // InlineScript needs to handle these specially, since it might go through the PowerShell AddScript() API.
        // If the parameter "CommandName" is in use, we add the preference configuration to the command parameters,
        // otherwise, we add the preference configuration to the preference variable.
        // All other activities have this set automatically by the infrastructure via parameters.
        private void UpdatePreferenceVariables(ActivityImplementationContext implementationContext)
        {
            System.Management.Automation.PowerShell        session = implementationContext.PowerShellInstance;
            System.Management.Automation.Runspaces.Command command = null;

            if (!_commandSpecified)
            {
                // "CommandName" and "Parameters" are in use
                command = session.Commands.Commands[0];
            }

            if (implementationContext.Verbose != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Verbose", implementationContext.Verbose);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Verbose.Value)
                    {
                        preference = ActionPreference.Continue;
                    }

                    implementationContext.PSActivityEnvironment.Variables["VerbosePreference"] = preference;
                }
            }

            if (implementationContext.Debug != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("Debug", implementationContext.Debug);
                }
                else
                {
                    // Map the boolean / switch to an actual action preference
                    ActionPreference preference = ActionPreference.SilentlyContinue;

                    if (implementationContext.Debug.Value)
                    {
                        preference = ActionPreference.Continue;
                    }

                    implementationContext.PSActivityEnvironment.Variables["DebugPreference"] = preference;
                }
            }

            if (implementationContext.WhatIf != null && command != null)
            {
                command.Parameters.Add("WhatIf", implementationContext.WhatIf);
            }

            if (implementationContext.ErrorAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("ErrorAction", implementationContext.ErrorAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["ErrorActionPreference"] = implementationContext.ErrorAction;
                }
            }

            if (implementationContext.WarningAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("WarningAction", implementationContext.WarningAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["WarningPreference"] = implementationContext.WarningAction;
                }
            }

            if (implementationContext.InformationAction != null)
            {
                if (command != null)
                {
                    command.Parameters.Add("InformationAction", implementationContext.InformationAction);
                }
                else
                {
                    implementationContext.PSActivityEnvironment.Variables["InformationPreference"] = implementationContext.InformationAction;
                }
            }
        }
        DebugShouldContinue(string message, ref ActionPreference actionPreference)
        {
            Dbg.Assert(actionPreference == ActionPreference.Inquire, "Why are you inquiring if your preference is not to?");

            bool shouldContinue = false;

            Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();

            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesLabel, InternalHostUserInterfaceStrings.ShouldContinueYesHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueYesToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueYesToAllHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoLabel, InternalHostUserInterfaceStrings.ShouldContinueNoHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueNoToAllLabel, InternalHostUserInterfaceStrings.ShouldContinueNoToAllHelp));
            choices.Add(new ChoiceDescription(InternalHostUserInterfaceStrings.ShouldContinueSuspendLabel, InternalHostUserInterfaceStrings.ShouldContinueSuspendHelp));

            bool endLoop = true;
            do
            {
                endLoop = true;

                switch (
                    PromptForChoice(
                        InternalHostUserInterfaceStrings.ShouldContinuePromptMessage,
                        message,
                        choices,
                        0))
                {
                    case 0:
                        shouldContinue = true;
                        break;

                    case 1:
                        actionPreference = ActionPreference.Continue;
                        shouldContinue = true;
                        break;

                    case 2:
                        shouldContinue = false;
                        break;

                    case 3:
                        // No to All means that we want to stop everytime WriteDebug is called. Since No throws an error, I
                        // think that ordinarily, the caller will terminate.  So I don't think the caller will ever get back
                        // calling WriteDebug again, and thus "No to All" might not be a useful option to have.

                        actionPreference = ActionPreference.Stop;
                        shouldContinue = false;
                        break;

                    case 4:
                        // This call returns when the user exits the nested prompt.

                        _parent.EnterNestedPrompt();
                        endLoop = false;
                        break;
                }//switch
            } while (endLoop != true);

            return shouldContinue;
        }
        WriteDebugLine(string message, ref ActionPreference preference)
        {
            string errorMsg = null;
            ErrorRecord errorRecord = null;
            switch (preference)
            {
                case ActionPreference.Continue:
                    WriteDebugLineHelper(message);
                    break;
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Ignore:
                    break;
                case ActionPreference.Inquire:
                    if (!DebugShouldContinue(message, ref preference))
                    {
                        // user asked to exit with an error

                        errorMsg = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
                        errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
                            "UserStopRequest", ErrorCategory.OperationStopped, null);
                        ActionPreferenceStopException e = new ActionPreferenceStopException(errorRecord);
                        // We cannot call ThrowTerminatingError since this is not a cmdlet or provider
                        throw e;
                    }
                    else
                    {
                        WriteDebugLineHelper(message);
                    }
                    break;
                case ActionPreference.Stop:
                    WriteDebugLineHelper(message);

                    errorMsg = InternalHostUserInterfaceStrings.WriteDebugLineStoppedError;
                    errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(errorMsg),
                        "ActionPreferenceStop", ErrorCategory.OperationStopped, null);
                    ActionPreferenceStopException ense = new ActionPreferenceStopException(errorRecord);
                    // We cannot call ThrowTerminatingError since this is not a cmdlet or provider
                    throw ense;
                default:
                    Dbg.Assert(false, "all preferences should be checked");
                    throw PSTraceSource.NewArgumentException("preference",
                        InternalHostUserInterfaceStrings.UnsupportedPreferenceError, preference);
                    // break;
            }
        }
Example #33
0
 internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = new ActionPreference?())
 {
     this.ThrowIfStopping();
     if ((errorRecord.ErrorDetails != null) && (errorRecord.ErrorDetails.TextLookupError != null))
     {
         Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
         errorRecord.ErrorDetails.TextLookupError = null;
         MshLog.LogCommandHealthEvent(this.context, textLookupError, Severity.Warning);
     }
     this.pipelineProcessor.ExecutionFailed = true;
     if (this.shouldLogPipelineExecutionDetail)
     {
         this.pipelineProcessor.LogExecutionError(this.thisCommand.MyInvocation, errorRecord);
     }
     ActionPreference errorAction = this.ErrorAction;
     if (actionPreference.HasValue)
     {
         errorAction = actionPreference.Value;
     }
     if (ActionPreference.Ignore != errorAction)
     {
         if (errorAction == ActionPreference.SilentlyContinue)
         {
             this.AppendErrorToVariables(errorRecord);
         }
         else
         {
             if (ContinueStatus.YesToAll == this.lastErrorContinueStatus)
             {
                 errorAction = ActionPreference.Continue;
             }
             switch (errorAction)
             {
                 case ActionPreference.Stop:
                 {
                     ActionPreferenceStopException e = new ActionPreferenceStopException(this.MyInvocation, errorRecord, this.CBResourcesBaseName, "ErrorPreferenceStop", new object[] { "ErrorActionPreference", errorRecord.ToString() });
                     throw this.ManageException(e);
                 }
                 case ActionPreference.Inquire:
                     this.lastErrorContinueStatus = this.InquireHelper(RuntimeException.RetrieveMessage(errorRecord), null, true, false, true);
                     break;
             }
             this.AppendErrorToVariables(errorRecord);
             PSObject obj2 = PSObject.AsPSObject(errorRecord);
             if (obj2.Members["writeErrorStream"] == null)
             {
                 PSNoteProperty member = new PSNoteProperty("writeErrorStream", true);
                 obj2.Properties.Add(member);
             }
             if (this.ErrorMergeTo != MergeDataStream.None)
             {
                 this.OutputPipe.AddWithoutAppendingOutVarList(obj2);
             }
             else
             {
                 this.ErrorOutputPipe.AddWithoutAppendingOutVarList(obj2);
             }
         }
     }
 }
		internal CimCmdletInvocationContext(CimCmdletDefinitionContext cmdletDefinitionContext, Cmdlet cmdlet, string namespaceOverride)
		{
			this._defaultCimSession = new Lazy<CimSession>(new Func<CimSession>(CimCmdletInvocationContext.CreateDefaultCimSession));
			this.CmdletDefinitionContext = cmdletDefinitionContext;
			this.NamespaceOverride = namespaceOverride;
			this.CmdletInvocationInfo = cmdlet.MyInvocation;
			MshCommandRuntime commandRuntime = cmdlet.CommandRuntime as MshCommandRuntime;
			this.DebugActionPreference = commandRuntime.DebugPreference;
			Cmdlet cmdlet1 = cmdlet;
			ActionPreference debugActionPreference = this.DebugActionPreference;
			string str = "Debug";
			Func<string> func = () => CmdletizationResources.CimCmdletAdapter_DebugInquire;
			CimCmdletInvocationContext.WarnAboutUnsupportedActionPreferences(cmdlet1, debugActionPreference, str, func, () => string.Empty);
			this.WarningActionPreference = commandRuntime.WarningPreference;
			Cmdlet cmdlet2 = cmdlet;
			ActionPreference warningActionPreference = this.WarningActionPreference;
			string str1 = "WarningAction";
			Func<string> func1 = () => CmdletizationResources.CimCmdletAdapter_WarningInquire;
			CimCmdletInvocationContext.WarnAboutUnsupportedActionPreferences(cmdlet2, warningActionPreference, str1, func1, () => CmdletizationResources.CimCmdletAdapter_WarningStop);
			this.VerboseActionPreference = commandRuntime.VerbosePreference;
			this.ErrorActionPreference = commandRuntime.ErrorAction;
			this.ShouldProcessOptimization = commandRuntime.CalculatePossibleShouldProcessOptimization();
		}
Example #35
0
        } // DoWriteError

        // NOTICE-2004/06/08-JonN 959638
        // Use this variant to skip the ThrowIfWriteNotPermitted check
        /// <exception cref="System.Management.Automation.PipelineStoppedException">
        /// The pipeline has already been terminated, or was terminated
        /// during the execution of this method.
        /// The Cmdlet should generally just allow PipelineStoppedException
        /// to percolate up to the caller of ProcessRecord etc.
        /// </exception>
        /// <remarks>
        /// If the pipeline is terminated due to ActionPreference.Stop
        /// or ActionPreference.Inquire, this method will throw
        /// <see cref="System.Management.Automation.PipelineStoppedException"/>,
        /// but the command failure will ultimately be
        /// <see cref="System.Management.Automation.ActionPreferenceStopException"/>,
        /// </remarks>
        internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = null, bool isNativeError = false)
        {
            ThrowIfStopping();

            if (null != errorRecord.ErrorDetails
                && null != errorRecord.ErrorDetails.TextLookupError)
            {
                Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
                errorRecord.ErrorDetails.TextLookupError = null;
                MshLog.LogCommandHealthEvent(
                    Context,
                    textLookupError,
                    Severity.Warning);
            }

            this.PipelineProcessor.ExecutionFailed = true;
            if (LogPipelineExecutionDetail)
            {
                this.PipelineProcessor.LogExecutionError(_thisCommand.MyInvocation, errorRecord);
            }

            ActionPreference preference = ErrorAction;
            if (actionPreference.HasValue)
            {
                preference = actionPreference.Value;
            }

            // No trace of the error in the 'Ignore' case
            if (ActionPreference.Ignore == preference)
            {
                return; // do not write or record to output pipe
            }

            // 2004/05/26-JonN
            // The object is not written in the SilentlyContinue case
            if (ActionPreference.SilentlyContinue == preference)
            {
                AppendErrorToVariables(errorRecord);
                return; // do not write to output pipe
            }

            if (ContinueStatus.YesToAll == lastErrorContinueStatus)
            {
                preference = ActionPreference.Continue;
            }

            switch (preference)
            {
                case ActionPreference.Stop:
                    ActionPreferenceStopException e =
                        new ActionPreferenceStopException(
                            MyInvocation,
                            errorRecord,
                            StringUtil.Format(CommandBaseStrings.ErrorPreferenceStop,
                                              "ErrorActionPreference",
                                              errorRecord.ToString()));
                    throw ManageException(e);

                case ActionPreference.Inquire:
                    // ignore return value
                    // this will throw if the user chooses not to continue
                    lastErrorContinueStatus = InquireHelper(
                        RuntimeException.RetrieveMessage(errorRecord),
                        null,
                        true,  // allowYesToAll
                        false, // allowNoToAll
                        true,  // replaceNoWithHalt
                        false  // hasSecurityImpact
                    );
                    break;
            } // switch (preference)

            // 2005/01/20 Do not write the object to $error if
            // ManageException has already done so
            AppendErrorToVariables(errorRecord);

            // Add this note property and set its value to true for F&O
            // to decide whether to call WriteErrorLine or WriteLine.
            // We want errors to print in red in both cases.
            PSObject errorWrap = PSObject.AsPSObject(errorRecord);
            // It's possible we've already added the member (this method is recursive sometimes
            // when tracing), so don't add the member again.

            // We don't add a note property on messages that comes from stderr stream.
            if (!isNativeError && errorWrap.Members["writeErrorStream"] == null)
            {
                PSNoteProperty note = new PSNoteProperty("writeErrorStream", true);
                errorWrap.Properties.Add(note);
            }

            // 2003/11/19-JonN Previously, PSObject instances in ErrorOutputPipe
            // wrapped the TargetObject and held the CoreException as a note.
            // Now, they wrap the CoreException and hold the TargetObject as a note.
            if (ErrorMergeTo != MergeDataStream.None)
            {
                Dbg.Assert(ErrorMergeTo == MergeDataStream.Output, "Only merging to success output is supported.");
                this.OutputPipe.AddWithoutAppendingOutVarList(errorWrap);
            }
            else
            {
                // If this is an error pipe for a hosting application and we are logging,
                // then create a temporary PowerShell to log the error.
                if (Context.InternalHost.UI.IsTranscribing)
                {
                    Context.InternalHost.UI.TranscribeError(Context, errorRecord.InvocationInfo, errorWrap);
                }

                this.ErrorOutputPipe.AddWithoutAppendingOutVarList(errorWrap);
            }
        }
Example #36
0
        internal bool WriteHelper_ShouldWrite(ActionPreference preference, ContinueStatus lastContinueStatus)
        {
            this.ThrowIfStopping();
            this.ThrowIfWriteNotPermitted(false);
            switch (lastContinueStatus)
            {
                case ContinueStatus.YesToAll:
                    return true;

                case ContinueStatus.NoToAll:
                    return false;
            }
            switch (preference)
            {
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Ignore:
                    return false;

                case ActionPreference.Stop:
                case ActionPreference.Continue:
                case ActionPreference.Inquire:
                    return true;
            }
            return true;
        }
Example #37
0
        internal ContinueStatus WriteHelper(string inquireCaption, string inquireMessage, ActionPreference preference, ContinueStatus lastContinueStatus, string preferenceVariableName, string message)
        {
            switch (lastContinueStatus)
            {
                case ContinueStatus.YesToAll:
                    return ContinueStatus.YesToAll;

                case ContinueStatus.NoToAll:
                    return ContinueStatus.NoToAll;
            }
            switch (preference)
            {
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Continue:
                case ActionPreference.Ignore:
                    return ContinueStatus.Yes;

                case ActionPreference.Stop:
                {
                    ActionPreferenceStopException exception = new ActionPreferenceStopException(this.MyInvocation, this.CBResourcesBaseName, "ErrorPreferenceStop", new object[] { preferenceVariableName, message });
                    throw this.ManageException(exception);
                }
                case ActionPreference.Inquire:
                    return this.InquireHelper(inquireMessage, inquireCaption, true, false, true);
            }
            ActionPreferenceStopException e = new ActionPreferenceStopException(this.MyInvocation, this.CBResourcesBaseName, "PreferenceInvalid", new object[] { preferenceVariableName, preference });
            throw this.ManageException(e);
        }
Example #38
0
 internal void WriteProgress(long sourceId, ProgressRecord progressRecord, bool overrideInquire)
 {
     if (progressRecord == null)
     {
         throw PSTraceSource.NewArgumentNullException("progressRecord");
     }
     if ((this.Host == null) || (this.Host.UI == null))
     {
         throw PSTraceSource.NewInvalidOperationException();
     }
     InternalHostUserInterface uI = this.Host.UI as InternalHostUserInterface;
     ActionPreference progressPreference = this.ProgressPreference;
     if (overrideInquire && (progressPreference == ActionPreference.Inquire))
     {
         progressPreference = ActionPreference.Continue;
     }
     if (this.WriteHelper_ShouldWrite(progressPreference, this.lastProgressContinueStatus))
     {
         uI.WriteProgress(sourceId, progressRecord);
     }
     this.lastProgressContinueStatus = this.WriteHelper(null, null, progressPreference, this.lastProgressContinueStatus, "ProgressPreference", progressRecord.Activity);
 }
		private static void WarnAboutUnsupportedActionPreferences(Cmdlet cmdlet, ActionPreference effectiveActionPreference, string nameOfCommandLineParameter, Func<string> inquireMessageGetter, Func<string> stopMessageGetter)
		{
			string str;
			ActionPreference actionPreference = effectiveActionPreference;
			if (actionPreference == ActionPreference.Stop)
			{
				str = stopMessageGetter();
			}
			else if (actionPreference == ActionPreference.Continue)
			{
				return;
			}
			else if (actionPreference == ActionPreference.Inquire)
			{
				str = inquireMessageGetter();
			}
			else
			{
				return;
			}
			bool flag = cmdlet.MyInvocation.BoundParameters.ContainsKey(nameOfCommandLineParameter);
			if (flag)
			{
				Exception argumentException = new ArgumentException(str);
				ErrorRecord errorRecord = new ErrorRecord(argumentException, "ActionPreferenceNotSupportedByCimCmdletAdapter", ErrorCategory.NotImplemented, null);
				cmdlet.ThrowTerminatingError(errorRecord);
			}
		}
        internal void WriteDebugLine(string message, ref ActionPreference preference)
        {
            ErrorRecord error = null;
            switch (preference)
            {
                case ActionPreference.SilentlyContinue:
                case ActionPreference.Ignore:
                    return;

                case ActionPreference.Stop:
                {
                    this.WriteDebugLineHelper(message);
                    error = new ErrorRecord(new ParentContainsErrorRecordException(InternalHostUserInterfaceStrings.WriteDebugLineStoppedError), "ActionPreferenceStop", ErrorCategory.OperationStopped, null);
                    ActionPreferenceStopException exception2 = new ActionPreferenceStopException(error);
                    throw exception2;
                }
                case ActionPreference.Continue:
                    this.WriteDebugLineHelper(message);
                    return;

                case ActionPreference.Inquire:
                    if (!this.DebugShouldContinue(message, ref preference))
                    {
                        error = new ErrorRecord(new ParentContainsErrorRecordException(InternalHostUserInterfaceStrings.WriteDebugLineStoppedError), "UserStopRequest", ErrorCategory.OperationStopped, null);
                        ActionPreferenceStopException exception = new ActionPreferenceStopException(error);
                        throw exception;
                    }
                    this.WriteDebugLineHelper(message);
                    return;
            }
            throw PSTraceSource.NewArgumentException("preference", "InternalHostUserInterfaceStrings", "UnsupportedPreferenceError", new object[] { (ActionPreference) preference });
        }