Example #1
0
 private bool CommandInfoMatches(CommandInfo commandInfo)
 {
     if (commandInfo != null)
     {
         if (this.CommandPattern.IsMatch(commandInfo.Name))
         {
             return true;
         }
         if ((!string.IsNullOrEmpty(commandInfo.ModuleName) && (this.Command.IndexOf('\\') != -1)) && this.CommandPattern.IsMatch(commandInfo.ModuleName + @"\" + commandInfo.Name))
         {
             return true;
         }
         ExternalScriptInfo info = commandInfo as ExternalScriptInfo;
         if (info != null)
         {
             if (info.Path.Equals(this.Command, StringComparison.OrdinalIgnoreCase))
             {
                 return true;
             }
             if (this.CommandPattern.IsMatch(Path.GetFileNameWithoutExtension(info.Path)))
             {
                 return true;
             }
         }
     }
     return false;
 }
Example #2
0
 internal void InternalDispose(bool isDisposing)
 {
     this.myInvocation = null;
     this.state = null;
     this.commandInfo = null;
     this.context = null;
 }
        /// <summary>
        /// Gets the command's "Synopsis" documentation section.
        /// </summary>
        /// <param name="commandInfo">The CommandInfo instance for the command.</param>
        /// <param name="runspace">The Runspace to use for getting command documentation.</param>
        /// <returns></returns>
        public static string GetCommandSynopsis(
            CommandInfo commandInfo, 
            Runspace runspace)
        {
            string synopsisString = string.Empty;

            PSObject helpObject = null;

            using (PowerShell powerShell = PowerShell.Create())
            {
                powerShell.Runspace = runspace;
                powerShell.AddCommand("Get-Help");
                powerShell.AddArgument(commandInfo);
                helpObject = powerShell.Invoke<PSObject>().FirstOrDefault();
            }

            if (helpObject != null)
            {
                // Extract the synopsis string from the object
                synopsisString =
                    (string)helpObject.Properties["synopsis"].Value ??
                    string.Empty;

                // Ignore the placeholder value for this field
                if (string.Equals(synopsisString, "SHORT DESCRIPTION", System.StringComparison.InvariantCultureIgnoreCase))
                {
                    synopsisString = string.Empty;
                }
            }

            return synopsisString;
        }
Example #4
0
 internal static void ToPSObjectForRemoting(CommandInfo commandInfo, PSObject psObject)
 {
     RemotingEncoder.ValueGetterDelegate<CommandTypes> valueGetter = null;
     RemotingEncoder.ValueGetterDelegate<string> delegate3 = null;
     RemotingEncoder.ValueGetterDelegate<string> delegate4 = null;
     RemotingEncoder.ValueGetterDelegate<SessionStateEntryVisibility> delegate5 = null;
     if (commandInfo != null)
     {
         if (valueGetter == null)
         {
             valueGetter = () => commandInfo.CommandType;
         }
         RemotingEncoder.AddNoteProperty<CommandTypes>(psObject, "CommandInfo_CommandType", valueGetter);
         if (delegate3 == null)
         {
             delegate3 = () => commandInfo.Definition;
         }
         RemotingEncoder.AddNoteProperty<string>(psObject, "CommandInfo_Definition", delegate3);
         if (delegate4 == null)
         {
             delegate4 = () => commandInfo.Name;
         }
         RemotingEncoder.AddNoteProperty<string>(psObject, "CommandInfo_Name", delegate4);
         if (delegate5 == null)
         {
             delegate5 = () => commandInfo.Visibility;
         }
         RemotingEncoder.AddNoteProperty<SessionStateEntryVisibility>(psObject, "CommandInfo_Visibility", delegate5);
     }
 }
Example #5
0
        // internals
        //internal string UnresolvedCommandName { get; }
        internal void SetDefinition(string definition, CommandManager cmdManager)
        {
            _definition = definition;

            ReferencedCommand = cmdManager.FindCommand(definition);
            ResolvedCommand = ReferencedCommand;
        }
Example #6
0
 internal void InternalDispose(bool isDisposing)
 {
     this.myInvocation = null;
     this.state        = null;
     this.commandInfo  = null;
     this.context      = null;
 }
Example #7
0
 private HelpCommentsParser(CommandInfo commandInfo, List<string> parameterDescriptions)
 {
     this._sections = new CommentHelpInfo();
     this._parameters = new Dictionary<string, string>();
     this._examples = new List<string>();
     this._inputs = new List<string>();
     this._outputs = new List<string>();
     this._links = new List<string>();
     FunctionInfo info = commandInfo as FunctionInfo;
     if (info != null)
     {
         this.scriptBlock = info.ScriptBlock;
         this.commandName = info.Name;
     }
     else
     {
         ExternalScriptInfo info2 = commandInfo as ExternalScriptInfo;
         if (info2 != null)
         {
             this.scriptBlock = info2.ScriptBlock;
             this.commandName = info2.Path;
         }
     }
     this.commandMetadata = commandInfo.CommandMetadata;
     this.parameterDescriptions = parameterDescriptions;
 }
Example #8
0
        /// <summary>
        /// Constructor for InvocationInfo object
        /// </summary>
        /// 
        /// <param name="commandInfo">
        /// The command information the invocation info represents.
        /// </param>
        /// 
        /// <param name="scriptPosition">
        /// The position representing the invocation, or the position representing the error.
        /// </param>
        /// 
        /// <param name="context">
        /// The context in which the InvocationInfo is being created.
        /// </param>
        /// 
        internal InvocationInfo(CommandInfo commandInfo, IScriptExtent scriptPosition, ExecutionContext context)
        {
            MyCommand = commandInfo;
            CommandOrigin = CommandOrigin.Internal;
            _scriptPosition = scriptPosition;

            ExecutionContext contextToUse = null;
            if ((commandInfo != null) && (commandInfo.Context != null))
            {
                contextToUse = commandInfo.Context;
            }
            else if (context != null)
            {
                contextToUse = context;
            }

            // Populate the history ID of this command
            if (contextToUse != null)
            {
                Runspaces.LocalRunspace localRunspace = contextToUse.CurrentRunspace as Runspaces.LocalRunspace;
                if (localRunspace != null && localRunspace.History != null)
                {
                    HistoryId = localRunspace.History.GetNextHistoryId();
                }
            }
        }
Example #9
0
 internal PseudoBindingInfo(System.Management.Automation.CommandInfo commandInfo, int defaultParameterSetFlag, Collection <AstParameterArgumentPair> allParsedArguments, List <MergedCompiledCommandParameter> unboundParameters)
 {
     this._commandInfo             = commandInfo;
     this._infoType                = PseudoBindingInfoType.PseudoBindingFail;
     this._defaultParameterSetFlag = defaultParameterSetFlag;
     this._allParsedArguments      = allParsedArguments;
     this._unboundParameters       = unboundParameters;
 }
 public ScaffolderInfo(string name, string packageName, string location, CommandInfo command, ScaffolderAttribute scaffolderAttribute)
 {
     Name = name;
     PackageName = packageName;
     Location = location;
     Command = command;
     ScaffolderAttribute = scaffolderAttribute;
 }
Example #11
0
 internal PseudoBindingInfo(System.Management.Automation.CommandInfo commandInfo, int defaultParameterSetFlag, Collection<AstParameterArgumentPair> allParsedArguments, List<MergedCompiledCommandParameter> unboundParameters)
 {
     this._commandInfo = commandInfo;
     this._infoType = PseudoBindingInfoType.PseudoBindingFail;
     this._defaultParameterSetFlag = defaultParameterSetFlag;
     this._allParsedArguments = allParsedArguments;
     this._unboundParameters = unboundParameters;
 }
Example #12
0
 internal Command(System.Management.Automation.CommandInfo commandInfo, bool isScript)
 {
     this._mergeInstructions = new PipelineResultTypes[4];
     this._parameters        = new CommandParameterCollection();
     this._command           = string.Empty;
     this._commandInfo       = commandInfo;
     this._command           = this._commandInfo.Name;
     this._isScript          = isScript;
 }
Example #13
0
 internal Command(System.Management.Automation.CommandInfo commandInfo, bool isScript)
 {
     this._mergeInstructions = new PipelineResultTypes[4];
     this._parameters = new CommandParameterCollection();
     this._command = string.Empty;
     this._commandInfo = commandInfo;
     this._command = this._commandInfo.Name;
     this._isScript = isScript;
 }
Example #14
0
 internal MshCommandRuntime(System.Management.Automation.ExecutionContext context, CommandInfo commandInfo, InternalCommand thisCommand)
 {
     this.context = context;
     this.host = context.EngineHostInterface;
     this.CBhost = context.EngineHostInterface;
     this.commandInfo = commandInfo;
     this.thisCommand = thisCommand;
     this.shouldLogPipelineExecutionDetail = this.InitShouldLogPipelineExecutionDetail();
 }
 public DocumentItem(String itemName, CommandInfo commandInfo, XElement xElement)
 {
   this.name = commandInfo.Name;
   this.itemName = itemName;
   this.commandInfo = commandInfo;
   this.xElement = xElement;
   
   GetProperties();
 }
Example #16
0
 internal InvocationInfo(PSObject psObject)
 {
     this._historyId = -1L;
     this._pipelineIterationInfo = new int[0];
     this._commandOrigin = (System.Management.Automation.CommandOrigin) SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_CommandOrigin");
     this._expectingInput = (bool) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ExpectingInput");
     this._invocationName = (string) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_InvocationName");
     this._historyId = (long) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_HistoryId");
     this._pipelineLength = (int) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelineLength");
     this._pipelinePosition = (int) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_PipelinePosition");
     string propertyValue = (string) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptName");
     int scriptLineNumber = (int) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_ScriptLineNumber");
     int offsetInLine = (int) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_OffsetInLine");
     string line = (string) SerializationUtilities.GetPropertyValue(psObject, "InvocationInfo_Line");
     System.Management.Automation.Language.ScriptPosition startPosition = new System.Management.Automation.Language.ScriptPosition(propertyValue, scriptLineNumber, offsetInLine, line);
     this._scriptPosition = new ScriptExtent(startPosition, startPosition);
     this._commandInfo = RemoteCommandInfo.FromPSObjectForRemoting(psObject);
     ArrayList psObjectPropertyBaseObject = (ArrayList) SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_PipelineIterationInfo");
     if (psObjectPropertyBaseObject != null)
     {
         this._pipelineIterationInfo = (int[]) psObjectPropertyBaseObject.ToArray(Type.GetType("System.Int32"));
     }
     else
     {
         this._pipelineIterationInfo = new int[0];
     }
     Hashtable hashtable = (Hashtable) SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_BoundParameters");
     Dictionary<string, object> dictionary = new Dictionary<string, object>();
     if (hashtable != null)
     {
         foreach (DictionaryEntry entry in hashtable)
         {
             dictionary.Add((string) entry.Key, entry.Value);
         }
     }
     this._boundParameters = dictionary;
     ArrayList list2 = (ArrayList) SerializationUtilities.GetPsObjectPropertyBaseObject(psObject, "InvocationInfo_UnboundArguments");
     this._unboundArguments = new List<object>();
     if (list2 != null)
     {
         foreach (object obj2 in list2)
         {
             this._unboundArguments.Add(obj2);
         }
     }
     object obj3 = SerializationUtilities.GetPropertyValue(psObject, "SerializeExtent");
     bool flag = false;
     if (obj3 != null)
     {
         flag = (bool) obj3;
     }
     if (flag)
     {
         this._displayScriptPosition = ScriptExtent.FromPSObjectForRemoting(psObject);
     }
 }
Example #17
0
        /// <summary>
        /// Initializes the base command processor class with the command metadata
        /// </summary>
        /// 
        /// <param name="commandInfo">
        /// The metadata about the command to run.
        /// </param>
        /// 
        internal CommandProcessorBase(
            CommandInfo commandInfo)
        {
            if (commandInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException("commandInfo");
            }

            CommandInfo = commandInfo;
        }
Example #18
0
 public static bool IsVisible(CommandOrigin origin, CommandInfo commandInfo)
 {
     if (origin == CommandOrigin.Internal)
     {
         return true;
     }
     if (commandInfo == null)
     {
         throw PSTraceSource.NewArgumentNullException("commandInfo");
     }
     return (commandInfo.Visibility == SessionStateEntryVisibility.Public);
 }
Example #19
0
 internal CommandInfo(CommandInfo other)
 {
     this._name = string.Empty;
     this._type = CommandTypes.Application;
     this._prefix = "";
     this._module = other._module;
     this._visibility = other._visibility;
     this._arguments = other._arguments;
     this.Context = other.Context;
     this._name = other._name;
     this._type = other._type;
     this._copiedCommand = other;
     this.DefiningLanguageMode = other.DefiningLanguageMode;
 }
Example #20
0
 internal PseudoBindingInfo(System.Management.Automation.CommandInfo commandInfo, int validParameterSetsFlags, int defaultParameterSetFalg, Dictionary<string, MergedCompiledCommandParameter> boundParameters, List<MergedCompiledCommandParameter> unboundParameters, Dictionary<string, AstParameterArgumentPair> boundArguments, Collection<string> boundPositionalParameter, Collection<AstParameterArgumentPair> allParsedArguments, Collection<CommandParameterAst> parametersNotFound, Collection<CommandParameterAst> ambiguousParameters, Collection<AstParameterArgumentPair> duplicateParameters)
 {
     this._commandInfo = commandInfo;
     this._infoType = PseudoBindingInfoType.PseudoBindingSucceed;
     this._validParameterSetsFlags = validParameterSetsFlags;
     this._defaultParameterSetFlag = defaultParameterSetFalg;
     this._boundParameters = boundParameters;
     this._unboundParameters = unboundParameters;
     this._boundArguments = boundArguments;
     this._boundPositionalParameter = boundPositionalParameter;
     this._allParsedArguments = allParsedArguments;
     this._parametersNotFound = parametersNotFound;
     this._ambiguousParameters = ambiguousParameters;
     this._duplicateParameters = duplicateParameters;
 }
Example #21
0
 internal PseudoBindingInfo(System.Management.Automation.CommandInfo commandInfo, int validParameterSetsFlags, int defaultParameterSetFalg, Dictionary <string, MergedCompiledCommandParameter> boundParameters, List <MergedCompiledCommandParameter> unboundParameters, Dictionary <string, AstParameterArgumentPair> boundArguments, Collection <string> boundPositionalParameter, Collection <AstParameterArgumentPair> allParsedArguments, Collection <CommandParameterAst> parametersNotFound, Collection <CommandParameterAst> ambiguousParameters, Collection <AstParameterArgumentPair> duplicateParameters)
 {
     this._commandInfo              = commandInfo;
     this._infoType                 = PseudoBindingInfoType.PseudoBindingSucceed;
     this._validParameterSetsFlags  = validParameterSetsFlags;
     this._defaultParameterSetFlag  = defaultParameterSetFalg;
     this._boundParameters          = boundParameters;
     this._unboundParameters        = unboundParameters;
     this._boundArguments           = boundArguments;
     this._boundPositionalParameter = boundPositionalParameter;
     this._allParsedArguments       = allParsedArguments;
     this._parametersNotFound       = parametersNotFound;
     this._ambiguousParameters      = ambiguousParameters;
     this._duplicateParameters      = duplicateParameters;
 }
Example #22
0
        // internals
        //internal string UnresolvedCommandName { get; }
        internal void Resolve()
        {
            //only set referenced command if found
            //aliases only cause errors when they are used, not at instanciation
            CommandInfo refInfo = null;
            try
            {
                refInfo = _cmdManager == null ? null : _cmdManager.FindCommand(Definition);
            }
            catch (CommandNotFoundException)
            {
            }

            _referencedCommand = refInfo;
            ResolvedCommand = _referencedCommand;
        }
Example #23
0
 private HelpCommentsParser(CommandInfo commandInfo, List<string> parameterDescriptions)
 {
     FunctionInfo fi = commandInfo as FunctionInfo;
     if (fi != null)
     {
         _scriptBlock = fi.ScriptBlock;
         _commandName = fi.Name;
     }
     else
     {
         ExternalScriptInfo si = commandInfo as ExternalScriptInfo;
         if (si != null)
         {
             _scriptBlock = si.ScriptBlock;
             _commandName = si.Path;
         }
     }
     _commandMetadata = commandInfo.CommandMetadata;
     _parameterDescriptions = parameterDescriptions;
 }
Example #24
0
        /// <summary>
        /// Creates an instance of the ShowCommandCommandInfo class based on a CommandInfo object
        /// </summary>
        /// 
        /// <param name="other">
        /// The object to wrap.
        /// </param>
        public ShowCommandCommandInfo(CommandInfo other)
        {
            if (null == other)
            {
                throw new ArgumentNullException("other");
            }

            this.Name = other.Name;
            this.ModuleName = other.ModuleName;
            this.CommandType = other.CommandType;
            this.Definition = other.Definition;

            // In a runspace with restricted security settings we catch
            // PSSecurityException when accessing ParameterSets because
            // ExternalScript commands may be evaluated.
            try
            {
                this.ParameterSets =
                    other.ParameterSets
                        .Select(x => new ShowCommandParameterSetInfo(x))
                        .ToList()
                        .AsReadOnly();
            }
            catch (PSSecurityException)
            {
                // Since we can't access the parameter sets of this command,
                // populate the ParameterSets property with an empty list
                // so that consumers don't trip on a null value.
                this.ParameterSets = new List<ShowCommandParameterSetInfo>().AsReadOnly();
            }
            catch (ParseException)
            {
                // Could not parse the given command so don't continue initializing it
                this.ParameterSets = new List<ShowCommandParameterSetInfo>().AsReadOnly();
            }

            if (other.Module != null)
            {
                this.Module = new ShowCommandModuleInfo(other.Module);
            }
        }
Example #25
0
 internal void ShouldRunInternal(CommandInfo commandInfo, CommandOrigin origin, PSHost host)
 {
     bool flag = false;
     bool flag2 = false;
     Exception reason = null;
     try
     {
         lock (this.policyCheckLock)
         {
             flag = this.ShouldRun(commandInfo, origin, host, out reason);
         }
     }
     catch (Exception exception2)
     {
         CommandProcessorBase.CheckForSevereException(exception2);
         reason = exception2;
         flag2 = true;
         flag = false;
     }
     if (!flag)
     {
         if (reason == null)
         {
             throw new PSSecurityException(AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason);
         }
         if (reason is PSSecurityException)
         {
             throw reason;
         }
         string message = reason.Message;
         if (flag2)
         {
             message = AuthorizationManagerBase.AuthorizationManagerDefaultFailureReason;
         }
         PSSecurityException exception3 = new PSSecurityException(message, reason);
         throw exception3;
     }
 }
Example #26
0
 protected internal virtual bool ShouldRun(CommandInfo commandInfo, CommandOrigin origin, PSHost host, out Exception reason)
 {
     reason = null;
     return true;
 }
 public void InvokePipeToOutput(CommandInfo commandInfo, Hashtable args, PipelineResultTypes pipelineResultTypes)
 {
     if (commandInfo == null) throw new ArgumentNullException("commandInfo");
     _invokeCommand.InvokeScript("param($c, $a) . $c @a", true, pipelineResultTypes, null, commandInfo, args);
 }
 public IEnumerable<PSObject> InvokeCaptureOutput(CommandInfo commandInfo, Hashtable args)
 {
     if (commandInfo == null) throw new ArgumentNullException("commandInfo");
     return _invokeCommand.InvokeScript("param($c, $a) return . $c @a", true, PipelineResultTypes.Output | PipelineResultTypes.Error, null, commandInfo, args);
 }
Example #29
0
 private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, CommandInfo result, ref Exception lastError)
 {
     int length = commandName.IndexOfAny(new char[] { ':', '\\' });
     if ((length == -1) || (commandName[length] == ':'))
     {
         return null;
     }
     string str = commandName.Substring(0, length);
     string str2 = commandName.Substring(length + 1, (commandName.Length - length) - 1);
     if ((string.IsNullOrEmpty(str) || string.IsNullOrEmpty(str2)) || str.EndsWith(".", StringComparison.Ordinal))
     {
         return null;
     }
     try
     {
         discoveryTracer.WriteLine("Executing module-qualified search: {0}", new object[] { commandName });
         context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
         CmdletInfo cmdlet = context.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
         if ((commandOrigin == CommandOrigin.Internal) || ((cmdlet != null) && (cmdlet.Visibility == SessionStateEntryVisibility.Public)))
         {
             List<PSModuleInfo> modules = context.Modules.GetModules(new string[] { str }, false);
             PSModuleInfo info2 = null;
             if ((modules == null) || (modules.Count == 0))
             {
                 CommandInfo commandInfo = new CmdletInfo("Import-Module", typeof(ImportModuleCommand), null, null, context) {
                     Visibility = cmdlet.Visibility
                 };
                 Command command = new Command(commandInfo);
                 Collection<PSModuleInfo> collection = null;
                 discoveryTracer.WriteLine("Attempting to load module: {0}", new object[] { str });
                 try
                 {
                     collection = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand(command).AddParameter("Name", str).AddParameter("Scope", "GLOBAL").AddParameter("ErrorAction", ActionPreference.Ignore).AddParameter("PassThru").AddParameter("WarningAction", ActionPreference.Ignore).AddParameter("Verbose", false).AddParameter("Debug", false).Invoke<PSModuleInfo>();
                 }
                 catch (Exception exception)
                 {
                     discoveryTracer.WriteLine("Encountered error importing module: {0}", new object[] { exception.Message });
                     lastError = exception;
                     CommandProcessorBase.CheckForSevereException(exception);
                 }
                 if ((collection == null) || (collection.Count == 0))
                 {
                     string resourceStr = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportModule, str);
                     CommandNotFoundException exception2 = new CommandNotFoundException(originalCommandName, lastError, "CouldNotAutoLoadModule", resourceStr, new object[0]);
                     throw exception2;
                 }
                 info2 = collection[0];
             }
             else
             {
                 info2 = modules[0];
             }
             if (info2.ExportedCommands.ContainsKey(str2))
             {
                 result = info2.ExportedCommands[str2];
             }
         }
         return result;
     }
     catch (CommandNotFoundException)
     {
         throw;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
     }
     finally
     {
         context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName);
     }
     return result;
 }
Example #30
0
 internal static void ShouldRun(ExecutionContext context, PSHost host, CommandInfo commandInfo, CommandOrigin commandOrigin)
 {
     try
     {
         if ((commandOrigin == CommandOrigin.Runspace) && (commandInfo.Visibility != SessionStateEntryVisibility.Public))
         {
             CommandNotFoundException exception = new CommandNotFoundException(commandInfo.Name, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
             throw exception;
         }
         context.AuthorizationManager.ShouldRunInternal(commandInfo, commandOrigin, host);
     }
     catch (PSSecurityException exception2)
     {
         MshLog.LogCommandHealthEvent(context, exception2, Severity.Warning);
         MshLog.LogCommandLifecycleEvent(context, CommandState.Terminated, commandInfo.Name);
         throw;
     }
 }
Example #31
0
        internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo, CommandOrigin commandOrigin, bool? useLocalScope, SessionStateInternal sessionState)
        {
            CommandProcessorBase base2 = null;
            FunctionInfo info3;
            CommandNotFoundException exception6;
            HashSet<string> set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            while (((commandInfo.CommandType == CommandTypes.Alias) && !set.Contains(commandInfo.Name)) && ((commandOrigin == CommandOrigin.Internal) || (commandInfo.Visibility == SessionStateEntryVisibility.Public)))
            {
                set.Add(commandInfo.Name);
                AliasInfo info = (AliasInfo) commandInfo;
                commandInfo = info.ResolvedCommand;
                if (commandInfo == null)
                {
                    commandInfo = LookupCommandInfo(info.Definition, commandOrigin, this._context);
                }
                if (commandInfo == null)
                {
                    CommandNotFoundException exception = new CommandNotFoundException(info.Name, null, "AliasNotResolvedException", DiscoveryExceptions.AliasNotResolvedException, new object[] { info.UnresolvedCommandName });
                    throw exception;
                }
                PSSQMAPI.IncrementData(CommandTypes.Alias);
            }
            ShouldRun(this._context, this._context.EngineHostInterface, commandInfo, commandOrigin);
            CommandTypes commandType = commandInfo.CommandType;
            if (commandType <= CommandTypes.ExternalScript)
            {
                switch (commandType)
                {
                    case CommandTypes.Function:
                    case CommandTypes.Filter:
                        goto Label_01E3;

                    case CommandTypes.Cmdlet:
                        base2 = new CommandProcessor((CmdletInfo) commandInfo, this._context);
                        goto Label_0260;

                    case CommandTypes.ExternalScript:
                    {
                        ExternalScriptInfo scriptInfo = (ExternalScriptInfo) commandInfo;
                        scriptInfo.SignatureChecked = true;
                        try
                        {
                            if (!this._context.IsSingleShell)
                            {
                                bool? nullable = useLocalScope;
                                base2 = this.CreateScriptProcessorForMiniShell(scriptInfo, nullable.HasValue ? nullable.GetValueOrDefault() : true, sessionState);
                            }
                            else
                            {
                                bool? nullable2 = useLocalScope;
                                base2 = this.CreateScriptProcessorForSingleShell(scriptInfo, this._context, nullable2.HasValue ? nullable2.GetValueOrDefault() : true, sessionState);
                            }
                            goto Label_0260;
                        }
                        catch (ScriptRequiresSyntaxException exception2)
                        {
                            CommandNotFoundException exception3 = new CommandNotFoundException(exception2.Message, exception2);
                            throw exception3;
                        }
                        catch (PSArgumentException exception4)
                        {
                            CommandNotFoundException exception5 = new CommandNotFoundException(commandInfo.Name, exception4, "ScriptRequiresInvalidFormat", DiscoveryExceptions.ScriptRequiresInvalidFormat, new object[0]);
                            throw exception5;
                        }
                        goto Label_01E3;
                    }
                }
                goto Label_023F;
            }
            if (commandType != CommandTypes.Application)
            {
                if (commandType == CommandTypes.Script)
                {
                    bool? nullable4 = useLocalScope;
                    base2 = CreateCommandProcessorForScript((ScriptInfo) commandInfo, this._context, nullable4.HasValue ? nullable4.GetValueOrDefault() : true, sessionState);
                    goto Label_0260;
                }
                if (commandType == CommandTypes.Workflow)
                {
                    goto Label_01E3;
                }
                goto Label_023F;
            }
            base2 = new NativeCommandProcessor((ApplicationInfo) commandInfo, this._context);
            goto Label_0260;
        Label_01E3:
            info3 = (FunctionInfo) commandInfo;
            bool? nullable3 = useLocalScope;
            base2 = CreateCommandProcessorForScript(info3, this._context, nullable3.HasValue ? nullable3.GetValueOrDefault() : true, sessionState);
            goto Label_0260;
        Label_023F:
            exception6 = new CommandNotFoundException(commandInfo.Name, null, "CommandNotFoundException", DiscoveryExceptions.CommandNotFoundException, new object[0]);
            throw exception6;
        Label_0260:
            PSSQMAPI.IncrementData(commandInfo.CommandType);
            base2.Command.CommandOriginInternal = commandOrigin;
            base2.Command.MyInvocation.InvocationName = commandInfo.Name;
            return base2;
        }
Example #32
0
 private static CommandInfo InvokeCommandNotFoundHandler(string commandName, ExecutionContext context, string originalCommandName, CommandOrigin commandOrigin, CommandInfo result)
 {
     EventHandler<CommandLookupEventArgs> commandNotFoundAction = context.EngineIntrinsics.InvokeCommand.CommandNotFoundAction;
     if (commandNotFoundAction != null)
     {
         discoveryTracer.WriteLine("Executing CommandNotFoundAction: {0}", new object[] { commandName });
         try
         {
             context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveCommandNotFound", originalCommandName);
             CommandLookupEventArgs e = new CommandLookupEventArgs(originalCommandName, commandOrigin, context);
             commandNotFoundAction(originalCommandName, e);
             result = e.Command;
         }
         catch (Exception exception)
         {
             CommandProcessorBase.CheckForSevereException(exception);
         }
         finally
         {
             context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveCommandNotFound", originalCommandName);
         }
     }
     return result;
 }
Example #33
0
 internal Command(System.Management.Automation.CommandInfo commandInfo) : this(commandInfo, false)
 {
 }
Example #34
0
 internal CommandProcessorBase(CommandInfo cmdInfo)
 {
     CommandInfo = cmdInfo;
     Parameters = new CommandParameterCollection();
 }
        private async Task<SymbolReference> FindDeclarationForBuiltinCommand(
            CommandInfo cmdInfo, 
            SymbolReference foundSymbol,
            Workspace workspace)
        {
            SymbolReference foundDefinition = null;
            if (cmdInfo != null)
            {
                int index = 0;
                ScriptFile[] nestedModuleFiles;

                CommandInfo commandInfo = await GetCommandInfo(foundSymbol.SymbolName);

                nestedModuleFiles =
                    GetBuiltinCommandScriptFiles(
                        commandInfo.Module,
                        workspace);

                while (foundDefinition == null && index < nestedModuleFiles.Length)
                {
                    foundDefinition =
                        AstOperations.FindDefinitionOfSymbol(
                            nestedModuleFiles[index].ScriptAst,
                            foundSymbol);

                    if (foundDefinition != null)
                    {
                        foundDefinition.FilePath = nestedModuleFiles[index].FilePath;
                    }

                    index++;
                }
            }

            return foundDefinition;
        }
        /// <summary>
        /// Search an alias help target.
        /// </summary>
        /// <remarks>
        /// This will,
        ///     a. use _sessionState object to get a list of alias that match the target.
        ///     b. for each alias, retrieve help info as in ExactMatchHelp.
        /// </remarks>
        /// <param name="helpRequest">Help request object.</param>
        /// <param name="searchOnlyContent">
        /// If true, searches for pattern in the help content. Individual
        /// provider can decide which content to search in.
        ///
        /// If false, searches for pattern in the command names.
        /// </param>
        /// <returns>A IEnumerable of helpinfo object.</returns>
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            // aliases do not have help content...so doing nothing in that case
            if (!searchOnlyContent)
            {
                string target     = helpRequest.Target;
                string pattern    = target;
                var    allAliases = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

                if (!WildcardPattern.ContainsWildcardCharacters(target))
                {
                    pattern += "*";
                }

                WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
                IDictionary <string, AliasInfo> aliasTable = _sessionState.Internal.GetAliasTable();

                foreach (string name in aliasTable.Keys)
                {
                    if (matcher.IsMatch(name))
                    {
                        HelpRequest exactMatchHelpRequest = helpRequest.Clone();
                        exactMatchHelpRequest.Target = name;
                        // Duplicates??
                        foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest))
                        {
                            // Component/Role/Functionality match is done only for SearchHelp
                            // as "get-help * -category alias" should not forwad help to
                            // CommandHelpProvider..(ExactMatchHelp does forward help to
                            // CommandHelpProvider)
                            if (!Match(helpInfo, helpRequest))
                            {
                                continue;
                            }

                            if (allAliases.Contains(name))
                            {
                                continue;
                            }

                            allAliases.Add(name);

                            yield return(helpInfo);
                        }
                    }
                }

                CommandSearcher searcher =
                    new CommandSearcher(
                        pattern,
                        SearchResolutionOptions.ResolveAliasPatterns, CommandTypes.Alias,
                        _context);

                while (searcher.MoveNext())
                {
                    CommandInfo current = ((IEnumerator <CommandInfo>)searcher).Current;

                    if (_context.CurrentPipelineStopping)
                    {
                        yield break;
                    }

                    AliasInfo alias = current as AliasInfo;

                    if (alias != null)
                    {
                        string      name = alias.Name;
                        HelpRequest exactMatchHelpRequest = helpRequest.Clone();
                        exactMatchHelpRequest.Target = name;

                        // Duplicates??
                        foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest))
                        {
                            // Component/Role/Functionality match is done only for SearchHelp
                            // as "get-help * -category alias" should not forwad help to
                            // CommandHelpProvider..(ExactMatchHelp does forward help to
                            // CommandHelpProvider)
                            if (!Match(helpInfo, helpRequest))
                            {
                                continue;
                            }

                            if (allAliases.Contains(name))
                            {
                                continue;
                            }

                            allAliases.Add(name);

                            yield return(helpInfo);
                        }
                    }
                }

                foreach (CommandInfo current in ModuleUtils.GetMatchingCommands(pattern, _context, helpRequest.CommandOrigin))
                {
                    if (_context.CurrentPipelineStopping)
                    {
                        yield break;
                    }

                    AliasInfo alias = current as AliasInfo;

                    if (alias != null)
                    {
                        string name = alias.Name;

                        HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(alias);

                        if (allAliases.Contains(name))
                        {
                            continue;
                        }

                        allAliases.Add(name);

                        yield return(helpInfo);
                    }
                }
            }
        }