Exemplo n.º 1
0
 protected override void ProcessRecord()
 {
     if (this._inputObject != AutomationNull.Value)
     {
         if (this.script != null)
         {
             object[] input = new object[] { this._inputObject };
             object   obj2  = this.script.DoInvokeReturnAsIs(false, ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, this.InputObject, input, AutomationNull.Value, new object[0]);
             if (this.toBoolSite.Target(this.toBoolSite, obj2))
             {
                 base.WriteObject(this.InputObject);
             }
         }
         else
         {
             if (this._valueNotSpecified && ((this._binaryOperator != TokenKind.Ieq) || !this._forceBooleanEvaluation))
             {
                 base.ThrowTerminatingError(ForEachObjectCommand.GenerateNameParameterError("Value", InternalCommandStrings.ValueNotSpecifiedForWhereObject, "ValueNotSpecifiedForWhereObject", null, new object[0]));
             }
             if ((!this._valueNotSpecified && (this._binaryOperator == TokenKind.Ieq)) && this._forceBooleanEvaluation)
             {
                 base.ThrowTerminatingError(ForEachObjectCommand.GenerateNameParameterError("Operator", InternalCommandStrings.OperatorNotSpecified, "OperatorNotSpecified", null, new object[0]));
             }
             bool   error = false;
             object obj3  = this.GetValue(ref error);
             if (!error)
             {
                 try
                 {
                     if ((this._binaryOperator == TokenKind.Is) || (this._binaryOperator == TokenKind.IsNot))
                     {
                         string str = this._value as string;
                         if (((str != null) && str.StartsWith("[", StringComparison.CurrentCulture)) && str.EndsWith("]", StringComparison.CurrentCulture))
                         {
                             this._value = str.Substring(1, str.Length - 2);
                         }
                     }
                     object obj4 = this.operationDelegate(obj3, this._value);
                     if (this.toBoolSite.Target(this.toBoolSite, obj4))
                     {
                         base.WriteObject(this.InputObject);
                     }
                 }
                 catch (PipelineStoppedException)
                 {
                     throw;
                 }
                 catch (ArgumentException exception)
                 {
                     ErrorRecord errorRecord = new ErrorRecord(PSTraceSource.NewArgumentException("BinaryOperator", "ParserStrings", "BadOperatorArgument", new object[] { this._binaryOperator, exception.Message }), "BadOperatorArgument", ErrorCategory.InvalidArgument, this._inputObject);
                     base.WriteError(errorRecord);
                 }
                 catch (Exception exception2)
                 {
                     CommandProcessorBase.CheckForSevereException(exception2);
                     ErrorRecord record2 = new ErrorRecord(PSTraceSource.NewInvalidOperationException("ParserStrings", "OperatorFailed", new object[] { this._binaryOperator, exception2.Message }), "OperatorFailed", ErrorCategory.InvalidOperation, this._inputObject);
                     base.WriteError(record2);
                 }
             }
         }
     }
 }
Exemplo n.º 2
0
 public object VisitContinueStatement(ContinueStatementAst continueStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(continueStatementAst));
 }
Exemplo n.º 3
0
 public object VisitExitStatement(ExitStatementAst exitStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(exitStatementAst));
 }
Exemplo n.º 4
0
 public object VisitForStatement(ForStatementAst forStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(forStatementAst));
 }
Exemplo n.º 5
0
 public object VisitCatchClause(CatchClauseAst catchClauseAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(catchClauseAst));
 }
Exemplo n.º 6
0
 public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(functionDefinitionAst));
 }
Exemplo n.º 7
0
 public object VisitSwitchStatement(SwitchStatementAst switchStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(switchStatementAst));
 }
Exemplo n.º 8
0
        /// <summary>
        /// Internal proxy for EnterNestedPrompt.
        /// </summary>
        /// <param name="callingCommand"></param>
        internal void EnterNestedPrompt(InternalCommand callingCommand)
        {
            // Ensure we are in control of the pipeline
            LocalRunspace localRunspace = null;

            // This needs to be in a try / catch, since the LocalRunspace cast
            // tries to verify that the host supports interactive sessions.
            // Tests hosts do not.
            try { localRunspace = this.Runspace as LocalRunspace; }
            catch (PSNotImplementedException) { }

            if (localRunspace != null)
            {
                Pipeline currentlyRunningPipeline = this.Runspace.GetCurrentlyRunningPipeline();

                if ((currentlyRunningPipeline != null) &&
                    (currentlyRunningPipeline == localRunspace.PulsePipeline))
                {
                    throw new InvalidOperationException();
                }
            }

            // NTRAID#Windows OS Bugs-986407-2004/07/29 When kumarp has done the configuration work in the engine, it
            // should include setting a bit that indicates that the initialization is complete, and code should be
            // added here to throw an exception if this function is called before that bit is set.

            if (NestedPromptCount < 0)
            {
                Dbg.Assert(false, "nested prompt counter should never be negative.");
                throw PSTraceSource.NewInvalidOperationException(
                          InternalHostStrings.EnterExitNestedPromptOutOfSync);
            }

            // Increment our nesting counter.  When we set the value of the variable, we will replace any existing variable
            // of the same name.  This is good, as any existing value is either 1) ours, and we have claim to replace it, or
            // 2) is a squatter, and we have claim to clobber it.

            ++NestedPromptCount;
            Context.SetVariable(SpecialVariables.NestedPromptCounterVarPath, NestedPromptCount);

            // On entering a subshell, save and reset values of certain bits of session state

            PromptContextData contextData = new PromptContextData();

            contextData.SavedContextData = Context.SaveContextData();
            contextData.SavedCurrentlyExecutingCommandVarValue = Context.GetVariableValue(SpecialVariables.CurrentlyExecutingCommandVarPath);
            contextData.SavedPSBoundParametersVarValue         = Context.GetVariableValue(SpecialVariables.PSBoundParametersVarPath);
            contextData.RunspaceAvailability = this.Context.CurrentRunspace.RunspaceAvailability;
            contextData.LanguageMode         = Context.LanguageMode;

            PSPropertyInfo commandInfoProperty = null;
            PSPropertyInfo stackTraceProperty  = null;
            object         oldCommandInfo      = null;
            object         oldStackTrace       = null;

            if (callingCommand != null)
            {
                Dbg.Assert(callingCommand.Context == Context, "I expect that the contexts should match");

                // Populate $CurrentlyExecutingCommand to facilitate debugging.  One of the gotchas is that we are going to want
                // to expose more and more debug info. We could just populate more and more local variables but that is probably
                // a lousy approach as it pollutes the namespace.  A better way to do it is to add NOTES to the variable value
                // object.

                PSObject newValue = PSObject.AsPSObject(callingCommand);

                commandInfoProperty = newValue.Properties["CommandInfo"];
                if (commandInfoProperty is null)
                {
                    newValue.Properties.Add(new PSNoteProperty("CommandInfo", callingCommand.CommandInfo));
                }
                else
                {
                    oldCommandInfo            = commandInfoProperty.Value;
                    commandInfoProperty.Value = callingCommand.CommandInfo;
                }

                stackTraceProperty = newValue.Properties["StackTrace"];
                if (stackTraceProperty is null)
                {
                    newValue.Properties.Add(new PSNoteProperty("StackTrace", new System.Diagnostics.StackTrace()));
                }
                else
                {
                    oldStackTrace            = stackTraceProperty.Value;
                    stackTraceProperty.Value = new System.Diagnostics.StackTrace();
                }

                Context.SetVariable(SpecialVariables.CurrentlyExecutingCommandVarPath, newValue);
            }

            _contextStack.Push(contextData);
            Dbg.Assert(_contextStack.Count == NestedPromptCount, "number of saved contexts should equal nesting count");

            Context.PSDebugTraceStep  = false;
            Context.PSDebugTraceLevel = 0;
            Context.ResetShellFunctionErrorOutputPipe();

            // Lock down the language in the nested prompt
            if (Context.HasRunspaceEverUsedConstrainedLanguageMode)
            {
                Context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            this.Context.CurrentRunspace.UpdateRunspaceAvailability(RunspaceAvailability.AvailableForNestedCommand, true);

            try
            {
                _externalHostRef.Value.EnterNestedPrompt();
            }
            catch
            {
                // So where things really go south is this path; which is possible for hosts (like our ConsoleHost)
                // that don't return from EnterNestedPrompt immediately.
                //      EnterNestedPrompt() starts
                //          ExitNestedPrompt() called
                //          EnterNestedPrompt throws

                ExitNestedPromptHelper();
                throw;
            }
            finally
            {
                if (commandInfoProperty != null)
                {
                    commandInfoProperty.Value = oldCommandInfo;
                }

                if (stackTraceProperty != null)
                {
                    stackTraceProperty.Value = oldStackTrace;
                }
            }

            Dbg.Assert(NestedPromptCount >= 0, "nestedPromptCounter should be greater than or equal to 0");
        }
        /// <summary>
        /// Handler to be used in cases, where setting the state is the
        /// only task being performed. This method also asserts
        /// if the specified event is valid for the current state of
        /// the state machine
        /// </summary>
        /// <param name="sender">sender of this event</param>
        /// <param name="eventArgs">event args</param>
        private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs eventArgs)
        {
            switch (eventArgs.StateEvent)
            {
            case RemoteSessionEvent.NegotiationCompleted:
            {
                Dbg.Assert(_state == RemoteSessionState.NegotiationReceived,
                           "State can be set to Established only when current state is NegotiationReceived");
                SetState(RemoteSessionState.Established, null);
            }
            break;

            case RemoteSessionEvent.NegotiationReceived:
            {
                Dbg.Assert(eventArgs.RemoteSessionCapability != null,
                           "State can be set to NegotiationReceived only when RemoteSessionCapability is not null");
                if (eventArgs.RemoteSessionCapability == null)
                {
                    throw PSTraceSource.NewArgumentException("eventArgs");
                }

                SetState(RemoteSessionState.NegotiationReceived, null);
            }
            break;

            case RemoteSessionEvent.NegotiationSendCompleted:
            {
                Dbg.Assert((_state == RemoteSessionState.NegotiationSending) || (_state == RemoteSessionState.NegotiationSendingOnConnect),
                           "Negotiating send can be completed only when current state is NegotiationSending");

                SetState(RemoteSessionState.NegotiationSent, null);
            }
            break;

            case RemoteSessionEvent.ConnectFailed:
            {
                Dbg.Assert(_state == RemoteSessionState.Connecting,
                           "A ConnectFailed event can be raised only when the current state is Connecting");

                SetState(RemoteSessionState.ClosingConnection, eventArgs.Reason);
            }
            break;

            case RemoteSessionEvent.CloseFailed:
            {
                SetState(RemoteSessionState.Closed, eventArgs.Reason);
            }
            break;

            case RemoteSessionEvent.CloseCompleted:
            {
                SetState(RemoteSessionState.Closed, eventArgs.Reason);
            }
            break;

            case RemoteSessionEvent.KeyRequested:
            {
                Dbg.Assert(_state == RemoteSessionState.Established,
                           "Server can request a key only after the client reaches the Established state");

                if (_state == RemoteSessionState.Established)
                {
                    SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason);
                }
            }
            break;

            case RemoteSessionEvent.KeyReceived:
            {
                Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent,
                           "Key Receiving can only be raised after reaching the Established state");

                if (_state == RemoteSessionState.EstablishedAndKeySent)
                {
                    Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null);
                    if (tmp != null)
                    {
                        tmp.Dispose();
                    }

                    _keyExchanged = true;
                    SetState(RemoteSessionState.Established, eventArgs.Reason);

                    if (_pendingDisconnect)
                    {
                        //session key exchange is complete, if there is a disconnect pending, process it now
                        _pendingDisconnect = false;
                        DoDisconnect(sender, eventArgs);
                    }
                }
            }
            break;

            case RemoteSessionEvent.KeySent:
            {
                Dbg.Assert(_state >= RemoteSessionState.Established,
                           "Client can send a public key only after reaching the Established state");

                Dbg.Assert(_keyExchanged == false, "Client should do key exchange only once");

                if (_state == RemoteSessionState.Established ||
                    _state == RemoteSessionState.EstablishedAndKeyRequested)
                {
                    SetState(RemoteSessionState.EstablishedAndKeySent, eventArgs.Reason);

                    // start the timer and wait
                    _keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ClientDefaultOperationTimeoutMs, Timeout.Infinite);
                }
            }
            break;

            case RemoteSessionEvent.DisconnectCompleted:
            {
                Dbg.Assert(_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting,
                           "DisconnectCompleted event received while state machine is in wrong state");

                if (_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting)
                {
                    SetState(RemoteSessionState.Disconnected, eventArgs.Reason);
                }
            }
            break;

            case RemoteSessionEvent.DisconnectFailed:
            {
                Dbg.Assert(_state == RemoteSessionState.Disconnecting,
                           "DisconnectCompleted event received while state machine is in wrong state");

                if (_state == RemoteSessionState.Disconnecting)
                {
                    SetState(RemoteSessionState.Disconnected, eventArgs.Reason);         //set state to disconnected even TODO. Put some ETW event describing the disconnect process failure
                }
            }
            break;

            case RemoteSessionEvent.ReconnectCompleted:
            {
                Dbg.Assert(_state == RemoteSessionState.Reconnecting,
                           "ReconnectCompleted event received while state machine is in wrong state");

                if (_state == RemoteSessionState.Reconnecting)
                {
                    SetState(RemoteSessionState.Established, eventArgs.Reason);
                }
            }
            break;
            } // switch...
        }
Exemplo n.º 10
0
        /// <summary>
        /// Opens the Uri. System's default application will be used
        /// to show the uri.
        /// </summary>
        /// <param name="uriToLaunch"></param>
        private void LaunchOnlineHelp(Uri uriToLaunch)
        {
            Diagnostics.Assert(uriToLaunch != null, "uriToLaunch should not be null");

            if (!uriToLaunch.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
                !uriToLaunch.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw PSTraceSource.NewInvalidOperationException(HelpErrors.ProtocolNotSupported,
                                                                 uriToLaunch.ToString(),
                                                                 "http",
                                                                 "https");
            }

            // we use this test hook is to avoid actually calling out to another process
            if (InternalTestHooks.BypassOnlineHelpRetrieval)
            {
                this.WriteObject(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                return;
            }

            Exception exception           = null;
            bool      wrapCaughtException = true;

            try
            {
                this.WriteVerbose(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                System.Diagnostics.Process browserProcess = new System.Diagnostics.Process();

                if (Platform.IsNanoServer || Platform.IsIoT)
                {
                    // We cannot open the URL in browser on headless SKUs.
                    wrapCaughtException = false;
                    exception           = PSTraceSource.NewInvalidOperationException(HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    browserProcess.StartInfo.FileName        = uriToLaunch.OriginalString;
                    browserProcess.StartInfo.UseShellExecute = true;
                    browserProcess.Start();
                }
            }
            catch (InvalidOperationException ioe)
            {
                exception = ioe;
            }
            catch (System.ComponentModel.Win32Exception we)
            {
                exception = we;
            }

            if (exception != null)
            {
                if (wrapCaughtException)
                {
                    throw PSTraceSource.NewInvalidOperationException(exception, HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    throw exception;
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Closes the content readers and writers in the content holder array.
        /// </summary>
        internal void CloseContent(List <ContentHolder> contentHolders, bool disposing)
        {
            if (contentHolders == null)
            {
                throw PSTraceSource.NewArgumentNullException("contentHolders");
            }

            foreach (ContentHolder holder in contentHolders)
            {
                try
                {
                    if (holder.Writer != null)
                    {
                        holder.Writer.Close();
                    }
                }
                catch (Exception e) // Catch-all OK. 3rd party callout
                {
                    // Catch all the exceptions caused by closing the writer
                    // and write out an error.

                    ProviderInvocationException providerException =
                        new ProviderInvocationException(
                            "ProviderContentCloseError",
                            SessionStateStrings.ProviderContentCloseError,
                            holder.PathInfo.Provider,
                            holder.PathInfo.Path,
                            e);

                    // Log a provider health event

                    MshLog.LogProviderHealthEvent(
                        this.Context,
                        holder.PathInfo.Provider.Name,
                        providerException,
                        Severity.Warning);

                    if (!disposing)
                    {
                        WriteError(
                            new ErrorRecord(
                                providerException.ErrorRecord,
                                providerException));
                    }
                }

                try
                {
                    if (holder.Reader != null)
                    {
                        holder.Reader.Close();
                    }
                }
                catch (Exception e) // Catch-all OK. 3rd party callout
                {
                    // Catch all the exceptions caused by closing the writer
                    // and write out an error.

                    ProviderInvocationException providerException =
                        new ProviderInvocationException(
                            "ProviderContentCloseError",
                            SessionStateStrings.ProviderContentCloseError,
                            holder.PathInfo.Provider,
                            holder.PathInfo.Path,
                            e);

                    // Log a provider health event

                    MshLog.LogProviderHealthEvent(
                        this.Context,
                        holder.PathInfo.Provider.Name,
                        providerException,
                        Severity.Warning);

                    if (!disposing)
                    {
                        WriteError(
                            new ErrorRecord(
                                providerException.ErrorRecord,
                                providerException));
                    }
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Implements the ProcessRecord() method for get-help command
        /// </summary>
        protected override void ProcessRecord()
        {
            try
            {
                this.Context.HelpSystem.OnProgress += new HelpSystem.HelpProgressHandler(HelpSystem_OnProgress);

                bool         failed       = false;
                HelpCategory helpCategory = ToHelpCategory(Category, ref failed);

                if (failed)
                {
                    return;
                }

                // Validate input parameters
                ValidateAndThrowIfError(helpCategory);

                HelpRequest helpRequest = new HelpRequest(this.Name, helpCategory);

                helpRequest.Provider        = _provider;
                helpRequest.Component       = Component;
                helpRequest.Role            = Role;
                helpRequest.Functionality   = Functionality;
                helpRequest.ProviderContext = new ProviderContext(
                    this.Path,
                    this.Context.Engine.Context,
                    this.SessionState.Path);
                helpRequest.CommandOrigin = this.MyInvocation.CommandOrigin;

                // the idea is to use yield statement in the help lookup to speed up
                // perceived user experience....So HelpSystem.GetHelp returns an
                // IEnumerable..
                IEnumerable <HelpInfo> helpInfos = this.Context.HelpSystem.GetHelp(helpRequest);
                // HelpCommand acts differently when there is just one help object and when
                // there are more than one object...so handling this behavior through
                // some variables.
                HelpInfo firstHelpInfoObject = null;
                int      countOfHelpInfos    = 0;
                foreach (HelpInfo helpInfo in helpInfos)
                {
                    // honor Ctrl-C from user.
                    if (IsStopping)
                    {
                        return;
                    }

                    if (0 == countOfHelpInfos)
                    {
                        firstHelpInfoObject = helpInfo;
                    }
                    else
                    {
                        // write first help object only once.
                        if (firstHelpInfoObject != null)
                        {
                            WriteObjectsOrShowOnlineHelp(firstHelpInfoObject, false);
                            firstHelpInfoObject = null;
                        }

                        WriteObjectsOrShowOnlineHelp(helpInfo, false);
                    }

                    countOfHelpInfos++;
                }

                _timer.Stop();

#if LEGACYTELEMETRY
                if (!string.IsNullOrEmpty(Name))
                {
                    Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI.ReportGetHelpTelemetry(Name, countOfHelpInfos, _timer.ElapsedMilliseconds, _updatedHelp);
                }
#endif
                // Write full help as there is only one help info object
                if (1 == countOfHelpInfos)
                {
                    WriteObjectsOrShowOnlineHelp(firstHelpInfoObject, true);
                }
                else if (_showOnlineHelp && (countOfHelpInfos > 1))
                {
                    throw PSTraceSource.NewInvalidOperationException(HelpErrors.MultipleOnlineTopicsNotSupported, "Online");
                }

                // show errors only if there is no wildcard search or VerboseHelpErrors is true.
                if (((countOfHelpInfos == 0) && (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target))) ||
                    this.Context.HelpSystem.VerboseHelpErrors)
                {
                    // Check if there is any error happened. If yes,
                    // pipe out errors.
                    if (this.Context.HelpSystem.LastErrors.Count > 0)
                    {
                        foreach (ErrorRecord errorRecord in this.Context.HelpSystem.LastErrors)
                        {
                            WriteError(errorRecord);
                        }
                    }
                }
            }
            finally
            {
                this.Context.HelpSystem.OnProgress -= new HelpSystem.HelpProgressHandler(HelpSystem_OnProgress);
                // finally clear the ScriptBlockAst -> Token[] cache
                this.Context.HelpSystem.ClearScriptBlockTokenCache();
            }
        }
Exemplo n.º 13
0
 internal static void ResetTracer()
 {
     s_activeTracer = s_classTracer;
 }
Exemplo n.º 14
0
 internal static void SetTracer(PSTraceSource t)
 {
     s_activeTracer = t;
 }
Exemplo n.º 15
0
 public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(namedAttributeArgumentAst));
 }
Exemplo n.º 16
0
        /// <summary>
        /// Sets the alias of the specified name to the specified value
        /// </summary>
        /// <param name="name">
        /// The name of the alias to set.
        /// </param>
        /// <param name="value">
        /// The new value for the alias.
        /// </param>
        /// <param name="writeItem">
        /// If true, the item that was set should be written to WriteItemObject.
        /// </param>
#pragma warning disable 0162
        internal override void SetSessionStateItem(string name, object value, bool writeItem)
        {
            Dbg.Diagnostics.Assert(
                !String.IsNullOrEmpty(name),
                "The caller should verify this parameter");

            AliasProviderDynamicParameters dynamicParameters =
                DynamicParameters as AliasProviderDynamicParameters;

            AliasInfo item = null;

            bool dynamicParametersSpecified = dynamicParameters != null && dynamicParameters.OptionsSet;

            if (value == null)
            {
                if (dynamicParametersSpecified)
                {
                    item = (AliasInfo)GetSessionStateItem(name);

                    if (item != null)
                    {
                        item.SetOptions(dynamicParameters.Options, Force);
                    }
                }
                else
                {
                    RemoveSessionStateItem(name);
                }
            }
            else
            {
                do // false loop
                {
                    string stringValue = value as string;
                    if (stringValue != null)
                    {
                        if (dynamicParametersSpecified)
                        {
                            item = SessionState.Internal.SetAliasValue(name, stringValue, dynamicParameters.Options, Force, Context.Origin);
                        }
                        else
                        {
                            item = SessionState.Internal.SetAliasValue(name, stringValue, Force, Context.Origin);
                        }

                        break;
                    }

                    AliasInfo alias = value as AliasInfo;
                    if (alias != null)
                    {
                        AliasInfo newAliasInfo =
                            new AliasInfo(
                                name,
                                alias.Definition,
                                this.Context.ExecutionContext,
                                alias.Options);

                        if (dynamicParametersSpecified)
                        {
                            newAliasInfo.SetOptions(dynamicParameters.Options, Force);
                        }

                        item = SessionState.Internal.SetAliasItem(newAliasInfo, Force, Context.Origin);
                        break;
                    }

                    throw PSTraceSource.NewArgumentException("value");
                } while (false);
            }

            if (writeItem && item != null)
            {
                WriteItemObject(item, item.Name, false);
            }
        }
Exemplo n.º 17
0
 public object VisitParameter(ParameterAst parameterAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(parameterAst));
 }
Exemplo n.º 18
0
 public object VisitMemberExpression(MemberExpressionAst memberExpressionAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(memberExpressionAst));
 }
Exemplo n.º 19
0
 public object VisitIfStatement(IfStatementAst ifStmtAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(ifStmtAst));
 }
Exemplo n.º 20
0
 public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(errorExpressionAst));
 }
Exemplo n.º 21
0
 public object VisitDataStatement(DataStatementAst dataStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(dataStatementAst));
 }
Exemplo n.º 22
0
 public object VisitScriptBlock(ScriptBlockAst scriptBlockAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(scriptBlockAst));
 }
Exemplo n.º 23
0
 public object VisitWhileStatement(WhileStatementAst whileStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(whileStatementAst));
 }
Exemplo n.º 24
0
 public object VisitNamedBlock(NamedBlockAst namedBlockAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(namedBlockAst));
 }
Exemplo n.º 25
0
 public object VisitBreakStatement(BreakStatementAst breakStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(breakStatementAst));
 }
Exemplo n.º 26
0
 public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(typeConstraintAst));
 }
Exemplo n.º 27
0
 public object VisitReturnStatement(ReturnStatementAst returnStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(returnStatementAst));
 }
Exemplo n.º 28
0
 public object VisitAttribute(AttributeAst attributeAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(attributeAst));
 }
Exemplo n.º 29
0
 public object VisitThrowStatement(ThrowStatementAst throwStatementAst)
 {
     throw PSTraceSource.NewArgumentException(nameof(throwStatementAst));
 }
Exemplo n.º 30
0
        /// <summary>
        /// Opens the Uri. System's default application will be used
        /// to show the uri.
        /// </summary>
        /// <param name="uriToLaunch"></param>
        private void LaunchOnlineHelp(Uri uriToLaunch)
        {
            Diagnostics.Assert(null != uriToLaunch, "uriToLaunch should not be null");

            if (!uriToLaunch.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) &&
                !uriToLaunch.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                throw PSTraceSource.NewInvalidOperationException(HelpErrors.ProtocolNotSupported,
                                                                 uriToLaunch.ToString(),
                                                                 "http",
                                                                 "https");
            }

            // we use this test hook is to avoid actually calling out to another process
            if (InternalTestHooks.BypassOnlineHelpRetrieval)
            {
                this.WriteObject(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                return;
            }

            Exception exception           = null;
            bool      wrapCaughtException = true;

            try
            {
                this.WriteVerbose(string.Format(CultureInfo.InvariantCulture, HelpDisplayStrings.OnlineHelpUri, uriToLaunch.OriginalString));
                System.Diagnostics.Process browserProcess = new System.Diagnostics.Process();
#if UNIX
                browserProcess.StartInfo.FileName  = Platform.IsLinux ? "xdg-open" : /* OS X */ "open";
                browserProcess.StartInfo.Arguments = uriToLaunch.OriginalString;
                browserProcess.Start();
#elif CORECLR
                // On FullCLR, ProcessStartInfo.UseShellExecute is true by default. This means that the shell will be used when starting the process.
                // On CoreCLR, UseShellExecute is not supported. To work around this, we check if there is a default browser in the system.
                // If there is, we lunch it to open the HelpURI. If there isn't, we error out.
                string webBrowserPath = GetDefaultWebBrowser();
                if (webBrowserPath == null)
                {
                    wrapCaughtException = false;
                    exception           = PSTraceSource.NewInvalidOperationException(HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    browserProcess.StartInfo           = new ProcessStartInfo(webBrowserPath);
                    browserProcess.StartInfo.Arguments = "\"" + uriToLaunch.OriginalString + "\"";
                    browserProcess.Start();
                }
#else
                browserProcess.StartInfo.FileName = uriToLaunch.OriginalString;
                browserProcess.Start();
#endif
            }
            catch (InvalidOperationException ioe)
            {
                exception = ioe;
            }
            catch (System.ComponentModel.Win32Exception we)
            {
                exception = we;
            }

            if (null != exception)
            {
                if (wrapCaughtException)
                {
                    throw PSTraceSource.NewInvalidOperationException(exception, HelpErrors.CannotLaunchURI, uriToLaunch.OriginalString);
                }
                else
                {
                    throw exception;
                }
            }
        }