Beispiel #1
0
		public virtual IUiEltCollection this[string infoString]
        {
            get
            {
                if (string.IsNullOrEmpty(infoString)) return null;
                
                try {
                    
                    if (null == this || 0 == this.Count) return null;
                    
                    const WildcardOptions options = WildcardOptions.IgnoreCase |
                                                    WildcardOptions.Compiled;
                    
                    var wildcardInfoString = 
                        new WildcardPattern(infoString, options);
                    
                    var queryByStringData = from collectionItem
                        in this._collectionHolder //.ToArray()
                            where wildcardInfoString.IsMatch(collectionItem.GetCurrent().Name) ||
                        wildcardInfoString.IsMatch(collectionItem.GetCurrent().AutomationId) ||
                        wildcardInfoString.IsMatch(collectionItem.GetCurrent().ClassName)
                        select collectionItem;
                    
                    return AutomationFactory.GetUiEltCollection(queryByStringData);
                }
                catch {
                    return null;
                    // return new IUiElement[] {};
                }
            }
        }
        protected override void ProcessRecord()
        {
            if (String.IsNullOrEmpty(Property))
            {
                if (Object == null)
                {
                    WriteObject(_existingProperties, true);
                }
                else
                {
                    WriteObject(Object.Properties, true);
                }
                return;
            }

            var wildcard = new WildcardPattern(Property + "*", WildcardOptions.IgnoreCase);
            if (Object == null)
            {
                WriteObject(from pair in _existingProperties
                            where wildcard.IsMatch(pair.Key)
                            select pair.Value, true);
            }
            else
            {
                WriteObject(from prop in Object.Properties
                            where wildcard.IsMatch(prop.LocalName)
                            select prop, true);
            }
        }
 protected override void ProcessRecord()
 {
    string[] templateFiles = XamlHelper.GetDataTemplates();
    foreach (string path in Filter)
    {
       var pat = new WildcardPattern(path);
       foreach (var file in templateFiles)
       {
          if (pat.IsMatch(file) || pat.IsMatch( Path.GetDirectoryName(file) ))
          {
             WriteObject(new FileInfo(file));
          }
       }
    }
 }
Beispiel #4
0
 private IEnumerable<PSModuleInfo> GetLoadedModulesByWildcard(string wildcardStr)
 {
     var wildcard = new WildcardPattern(wildcardStr, WildcardOptions.IgnoreCase);
     var modules = from modPair in ExecutionContext.SessionState.LoadedModules.GetAll()
         where wildcard.IsMatch(modPair.Value.Name) select modPair.Value;
     return modules;
 }
        IEnumerable<DynamicMemberDescriptor> AddWildcardDynamicMembers(DynamicMemberSpecification spec, WildcardPattern pattern, PSObject ps, string proxyPropertyName)
        {
            var props = ps.Properties;
            var scriptFormat = "$this.'{0}'";
            if (null != proxyPropertyName)
            {
                props = ps.Properties[proxyPropertyName].ToPSObject().Properties;
                scriptFormat = "$this.'{1}'.'{0}'";
            }
            var matchingPropertyNames = from prop in props
                                        where pattern.IsMatch(prop.Name)
                                        select prop.Name;

            var members = matchingPropertyNames.ToList().ConvertAll(
                s => new
                {
                    PropertyName = s,
                    Member = new PSScriptProperty(
                         (proxyPropertyName ?? "" ) + "_" + s,
                         System.Management.Automation.ScriptBlock.Create(String.Format(scriptFormat, s,
                                                                                       proxyPropertyName))
                         )
                });
            return (from m in members
                    let s = (from sd in spec.ScaleDescriptors
                                 where sd.Key.IsMatch(m.PropertyName)
                                 select sd.Value).FirstOrDefault()
                    select new DynamicMemberDescriptor(m.Member, s)).ToList();
        }
Beispiel #6
0
 internal override PSObject[] GetParameter(string pattern)
 {
     if (((this.FullHelp == null) || (this.FullHelp.Properties["parameters"] == null)) || (this.FullHelp.Properties["parameters"].Value == null))
     {
         return base.GetParameter(pattern);
     }
     PSObject obj2 = PSObject.AsPSObject(this.FullHelp.Properties["parameters"].Value);
     if (obj2.Properties["parameter"] == null)
     {
         return base.GetParameter(pattern);
     }
     PSObject[] objArray = (PSObject[]) LanguagePrimitives.ConvertTo(obj2.Properties["parameter"].Value, typeof(PSObject[]), CultureInfo.InvariantCulture);
     if (string.IsNullOrEmpty(pattern))
     {
         return objArray;
     }
     List<PSObject> list = new List<PSObject>();
     WildcardPattern pattern2 = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
     foreach (PSObject obj3 in objArray)
     {
         if ((obj3.Properties["name"] != null) && (obj3.Properties["name"].Value != null))
         {
             string input = obj3.Properties["name"].Value.ToString();
             if (pattern2.IsMatch(input))
             {
                 list.Add(obj3);
             }
         }
     }
     return list.ToArray();
 }
        // Returns a RoleNamesCollection based on instances in the roleInstanceList
        // whose RoleInstance.RoleName matches the roleName passed in.  Wildcards
        // are handled for the roleName passed in.
        // This function also verifies that the RoleInstance exists before adding the
        // RoleName to the RoleNamesCollection.
        public static RoleNamesCollection GetRoleNames(RoleInstanceList roleInstanceList, string roleName)
        {
            var roleNamesCollection = new RoleNamesCollection();
            if (!string.IsNullOrEmpty(roleName))
            {
                if (WildcardPattern.ContainsWildcardCharacters(roleName))
                {
                    WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.Compiled;
                    WildcardPattern wildcardPattern = new WildcardPattern(roleName, wildcardOptions);

                    foreach (RoleInstance role in roleInstanceList)
                        if (!string.IsNullOrEmpty(role.RoleName) && wildcardPattern.IsMatch(role.RoleName))
                        {
                            roleNamesCollection.Add(role.RoleName);
                        }
                }
                else
                {
                    var roleInstance = roleInstanceList.Where(r => r.RoleName != null).
                        FirstOrDefault(r => r.RoleName.Equals(roleName, StringComparison.InvariantCultureIgnoreCase));
                    if (roleInstance != null)
                    {
                        roleNamesCollection.Add(roleName);
                    }
                }
            }
            return roleNamesCollection;
        }
Beispiel #8
0
 protected override string[] ExpandPath(string path)
 {
     var wildcard = new WildcardPattern(path, WildcardOptions.IgnoreCase);
     return (from i in _defaultDrive.Items.Keys
                      where wildcard.IsMatch(i)
                      select i).ToArray();
 }
Beispiel #9
0
 internal override bool MatchPatternInContent(WildcardPattern pattern)
 {
     string synopsis = this.Synopsis;
     string answers = this.Answers;
     if (synopsis == null)
     {
         synopsis = string.Empty;
     }
     if (this.Answers == null)
     {
         answers = string.Empty;
     }
     if (!pattern.IsMatch(synopsis))
     {
         return pattern.IsMatch(answers);
     }
     return true;
 }
Beispiel #10
0
 internal override bool MatchPatternInContent(WildcardPattern pattern)
 {
     string synopsis = this.Synopsis;
     string detailedDescription = this.DetailedDescription;
     if (synopsis == null)
     {
         synopsis = string.Empty;
     }
     if (detailedDescription == null)
     {
         detailedDescription = string.Empty;
     }
     if (!pattern.IsMatch(synopsis))
     {
         return pattern.IsMatch(detailedDescription);
     }
     return true;
 }
Beispiel #11
0
 internal Collection<PSTraceSource> GetMatchingTraceSource(string[] patternsToMatch, bool writeErrorIfMatchNotFound, out Collection<string> notMatched)
 {
     notMatched = new Collection<string>();
     Collection<PSTraceSource> collection = new Collection<PSTraceSource>();
     foreach (string str in patternsToMatch)
     {
         bool flag = false;
         if (string.IsNullOrEmpty(str))
         {
             notMatched.Add(str);
         }
         else
         {
             WildcardPattern pattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
             foreach (PSTraceSource source in PSTraceSource.TraceCatalog.Values)
             {
                 if (pattern.IsMatch(source.FullName))
                 {
                     flag = true;
                     collection.Add(source);
                 }
                 else if (pattern.IsMatch(source.Name))
                 {
                     flag = true;
                     collection.Add(source);
                 }
             }
             if (!flag)
             {
                 notMatched.Add(str);
                 if (writeErrorIfMatchNotFound && !WildcardPattern.ContainsWildcardCharacters(str))
                 {
                     ItemNotFoundException replaceParentContainsErrorRecordException = new ItemNotFoundException(str, "TraceSourceNotFound", SessionStateStrings.TraceSourceNotFound);
                     ErrorRecord errorRecord = new ErrorRecord(replaceParentContainsErrorRecordException.ErrorRecord, replaceParentContainsErrorRecordException);
                     base.WriteError(errorRecord);
                 }
             }
         }
     }
     return collection;
 }
Beispiel #12
0
 internal Collection<PSSnapInInfo> GetPSSnapIns(WildcardPattern wildcard)
 {
     Collection<PSSnapInInfo> matches = new Collection<PSSnapInInfo>();
     foreach (var pair in _snapins)
     {
         if (wildcard.IsMatch(pair.Key))
         {
             matches.Add(pair.Value);
         }
     }
     return matches;
 }
Beispiel #13
0
 private static bool Match(string target, string pattern)
 {
     if (string.IsNullOrEmpty(pattern))
     {
         return true;
     }
     if (string.IsNullOrEmpty(target))
     {
         target = "";
     }
     WildcardPattern pattern2 = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
     return pattern2.IsMatch(target);
 }
Beispiel #14
0
 internal void Extract(string entryPath)
 {
     if (WildcardPattern.ContainsWildcardCharacters(entryPath))
     {
         Command.WriteVerbose("Using wildcard extraction.");
         var pattern = new WildcardPattern(entryPath, WildcardOptions.IgnoreCase);
         Extract(entry => pattern.IsMatch(entry.Path));
     }
     else
     {
         // todo: fix ignorecase
         Extract(entry => entry.Path.Equals(entryPath,
             StringComparison.OrdinalIgnoreCase));
     }
 }
Beispiel #15
0
        protected override void ProcessRecord()
        {
            if (Id.HasValue)
            {
                WriteObject(_controller.GetDevice(Id.Value));
            }
            else
            {
                var wildCard = new WildcardPattern(Name, WildcardOptions.IgnoreCase);

                WriteObject(
                    _controller.GetDevices()
                        .FirstOrDefault(x => wildCard.IsMatch(x.Name)));
            }
        }
Beispiel #16
0
        public static IEnumerable <IPackage> FilterOnName(IEnumerable <IPackage> pkgs, string searchTerm, bool useWildCard)
        {
            if (useWildCard)
            {
                // Applying the wildcard pattern matching
                const SMA.WildcardOptions wildcardOptions = SMA.WildcardOptions.CultureInvariant | SMA.WildcardOptions.IgnoreCase;
                var wildcardPattern = new SMA.WildcardPattern(searchTerm, wildcardOptions);

                return(pkgs.Where(p => wildcardPattern.IsMatch(p.Id)));
            }
            else
            {
                return(pkgs.Where(each => each.Id.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase) > -1));
            }
        }
    	// 20140215
        // public static IEnumerable GetElementsByWildcard(this IUiEltCollection collection, string name, string automationId, string className, string txtValue, bool caseSensitive = false)
        public static IEnumerable GetElementsByWildcard(this IUiEltCollection collection, string name, string automationId, string className, string txtValue, bool caseSensitive)
        {
            WildcardOptions options;
            if (caseSensitive) {
                options =
                    WildcardOptions.Compiled;
            } else {
                options =
                    WildcardOptions.IgnoreCase |
                    WildcardOptions.Compiled;
            }
            
            List<IUiElement> list = collection.Cast<IUiElement>().ToList();
            
            var wildcardName = 
                new WildcardPattern((string.IsNullOrEmpty(name) ? "*" : name), options);
            var wildcardAutomationId = 
                new WildcardPattern((string.IsNullOrEmpty(automationId) ? "*" : automationId), options);
            var wildcardClassName = 
                new WildcardPattern((string.IsNullOrEmpty(className) ? "*" : className), options);
            var wildcardValue = 
                new WildcardPattern((string.IsNullOrEmpty(txtValue) ? "*" : txtValue), options);
            
            var queryByBigFour = from collectionItem
                in list
                // 20140312
//                where wildcardName.IsMatch(collectionItem.Current.Name) &&
//                      wildcardAutomationId.IsMatch(collectionItem.Current.AutomationId) &&
//                      wildcardClassName.IsMatch(collectionItem.Current.ClassName) &&
                    where wildcardName.IsMatch(collectionItem.GetCurrent().Name) &&
                wildcardAutomationId.IsMatch(collectionItem.GetCurrent().AutomationId) &&
                wildcardClassName.IsMatch(collectionItem.GetCurrent().ClassName) &&
                      // 20131209
                      // (collectionItem.GetSupportedPatterns().Contains(classic.ValuePattern.Pattern) ?
                      (collectionItem.GetSupportedPatterns().AsQueryable<IBasePattern>().Any<IBasePattern>(p => p is IValuePattern) ?
                      // 20131208
                      // wildcardValue.IsMatch((collectionItem.GetCurrentPattern(classic.ValuePattern.Pattern) as IValuePattern).Current.Value) :
                      // wildcardValue.IsMatch((collectionItem.GetCurrentPattern<IValuePattern, ValuePattern>(classic.ValuePattern.Pattern) as IValuePattern).Current.Value) :
                      wildcardValue.IsMatch(collectionItem.GetCurrentPattern<IValuePattern>(classic.ValuePattern.Pattern).Current.Value) :
                      // check whether the -Value parameter has or hasn't value
                      ("*" == txtValue ? true : false))
                select collectionItem;
            
            // disposal
            list = null;
            
            return queryByBigFour;
        }
Beispiel #18
0
        /// <summary>
        /// Returns help information for a parameter(s) identified by pattern
        /// </summary>
        /// <param name="pattern">pattern to search for parameters</param>
        /// <returns>A collection of parameters that match pattern</returns>
        internal override PSObject[] GetParameter(string pattern)
        {
            // this object knows Maml format...
            // So retrieve parameter information as per the format..
            if ((this.FullHelp == null) ||
                (this.FullHelp.Properties["parameters"] == null) ||
                (this.FullHelp.Properties["parameters"].Value == null))
            {
                // return the default..
                return(base.GetParameter(pattern));
            }

            PSObject prmts = PSObject.AsPSObject(this.FullHelp.Properties["parameters"].Value);

            if (prmts.Properties["parameter"] == null)
            {
                return(base.GetParameter(pattern));
            }

            PSObject[] prmtArray = (PSObject[])LanguagePrimitives.ConvertTo(
                prmts.Properties["parameter"].Value,
                typeof(PSObject[]),
                CultureInfo.InvariantCulture);

            if (string.IsNullOrEmpty(pattern))
            {
                return(prmtArray);
            }

            List <PSObject> returnList = new List <PSObject>();
            WildcardPattern matcher    = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            foreach (PSObject prmtr in prmtArray)
            {
                if ((prmtr.Properties["name"] == null) || (prmtr.Properties["name"].Value == null))
                {
                    continue;
                }

                string prmName = prmtr.Properties["name"].Value.ToString();
                if (matcher.IsMatch(prmName))
                {
                    returnList.Add(prmtr);
                }
            }

            return(returnList.ToArray());
        }
        protected override void ProcessRecord()
        {
            var config = GetConfiguration();

            var devices = config.Devices;
            if (!String.IsNullOrEmpty(Name))
            {
                var pattern = new WildcardPattern(Name, WildcardOptions.IgnoreCase);
                devices = devices.Where(d => pattern.IsMatch(d.Name));
            }

            foreach (var device in devices)
            {
                WriteObject(device);
            }
        }
        private static bool Match(string target, string pattern)
        {
            if (string.IsNullOrEmpty(pattern))
            {
                return(true);
            }

            if (string.IsNullOrEmpty(target))
            {
                target = string.Empty;
            }

            WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);

            return(matcher.IsMatch(target));
        }
Beispiel #21
0
        private bool FindTypeByModulePath(WildcardPattern classNameMatcher)
        {
            bool matchFound = false;

            var moduleList = ModuleUtils.GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, _context);

            foreach (var modulePath in moduleList)
            {
                string expandedModulePath = IO.Path.GetFullPath(modulePath);
                var    cachedClasses      = AnalysisCache.GetExportedClasses(expandedModulePath, _context);

                if (cachedClasses != null)
                {
                    //Exact match
                    if (!_useWildCards)
                    {
                        if (cachedClasses.ContainsKey(_className))
                        {
                            var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath);
                            if (classInfo != null)
                            {
                                _matchingClassList.Add(classInfo);
                                matchFound = true;
                            }
                        }
                    }
                    else
                    {
                        foreach (var className in cachedClasses.Keys)
                        {
                            if (classNameMatcher.IsMatch(className))
                            {
                                var classInfo = CachedItemToPSClassInfo(classNameMatcher, modulePath);
                                if (classInfo != null)
                                {
                                    _matchingClassList.Add(classInfo);
                                    matchFound = true;
                                }
                            }
                        }
                    }
                }
            }

            return(matchFound);
        }
Beispiel #22
0
        private CommandInfo GetNextFunction()
        {
            CommandInfo current = null;

            if ((this.commandResolutionOptions & SearchResolutionOptions.ResolveFunctionPatterns) != SearchResolutionOptions.None)
            {
                if (this.matchingFunctionEnumerator == null)
                {
                    Collection <CommandInfo> collection = new Collection <CommandInfo>();
                    WildcardPattern          pattern    = new WildcardPattern(this.commandName, WildcardOptions.IgnoreCase);
                    foreach (DictionaryEntry entry in this._context.EngineSessionState.GetFunctionTable())
                    {
                        if (pattern.IsMatch((string)entry.Key))
                        {
                            collection.Add((CommandInfo)entry.Value);
                        }
                    }
                    CommandInfo functionFromModules = this.GetFunctionFromModules(this.commandName);
                    if (functionFromModules != null)
                    {
                        collection.Add(functionFromModules);
                    }
                    this.matchingFunctionEnumerator = collection.GetEnumerator();
                }
                if (!this.matchingFunctionEnumerator.MoveNext())
                {
                    this.currentState = SearchState.SearchingCmdlets;
                    this.matchingFunctionEnumerator = null;
                }
                else
                {
                    current = this.matchingFunctionEnumerator.Current;
                }
            }
            else
            {
                this.currentState = SearchState.SearchingCmdlets;
                current           = this.GetFunction(this.commandName);
            }
            if ((current != null) && ((((PSLanguageMode)current.DefiningLanguageMode) == PSLanguageMode.ConstrainedLanguage) && (this._context.LanguageMode == PSLanguageMode.FullLanguage)))
            {
                current = null;
            }
            return(current);
        }
Beispiel #23
0
        private bool CheckTypeNames(JobSourceAdapter sourceAdapter, string[] jobSourceAdapterTypes)
        {
            if ((jobSourceAdapterTypes == null) || (jobSourceAdapterTypes.Length == 0))
            {
                return(true);
            }
            string adapterName = this.GetAdapterName(sourceAdapter);

            foreach (string str2 in jobSourceAdapterTypes)
            {
                WildcardPattern pattern = new WildcardPattern(str2, WildcardOptions.IgnoreCase);
                if (pattern.IsMatch(adapterName))
                {
                    return(true);
                }
            }
            return(false);
        }
Beispiel #24
0
        private CmdletInfo GetNextCmdlet()
        {
            CmdletInfo result = null;

            if (this.matchingCmdlet == null)
            {
                if ((this.commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != SearchResolutionOptions.None)
                {
                    Collection <CmdletInfo> collection = new Collection <CmdletInfo>();
                    PSSnapinQualifiedName   instance   = PSSnapinQualifiedName.GetInstance(this.commandName);
                    if (instance == null)
                    {
                        return(result);
                    }
                    WildcardPattern pattern = new WildcardPattern(instance.ShortName, WildcardOptions.IgnoreCase);
                    foreach (List <CmdletInfo> list in this._context.EngineSessionState.GetCmdletTable().Values)
                    {
                        foreach (CmdletInfo info2 in list)
                        {
                            if (pattern.IsMatch(info2.Name) && (string.IsNullOrEmpty(instance.PSSnapInName) || instance.PSSnapInName.Equals(info2.ModuleName, StringComparison.OrdinalIgnoreCase)))
                            {
                                collection.Add(info2);
                            }
                        }
                    }
                    this.matchingCmdlet = collection.GetEnumerator();
                }
                else
                {
                    this.matchingCmdlet = this._context.CommandDiscovery.GetCmdletInfo(this.commandName, (this.commandResolutionOptions & SearchResolutionOptions.SearchAllScopes) != SearchResolutionOptions.None);
                }
            }
            if (!this.matchingCmdlet.MoveNext())
            {
                this.currentState   = SearchState.SearchingBuiltinScripts;
                this.matchingCmdlet = null;
            }
            else
            {
                result = this.matchingCmdlet.Current;
            }
            return(traceResult(result));
        }
Beispiel #25
0
 protected override void EndProcessing()
 {
     if (All)
     {
         WriteObject(Plastic.GetWorkspaces(), true);
     }
     else
     {
         var currentDir = SessionState.Path.CurrentFileSystemLocation.ProviderPath;
         foreach (var wi in Plastic.GetWorkspaces())
         {
             var pattern = new WildcardPattern(wi.Path + "*", WildcardOptions.IgnoreCase);
             if (pattern.IsMatch(currentDir))
             {
                 WriteObject(wi);
             }
         }
     }
 }
Beispiel #26
0
        private static IEnumerable <CimModule> GetCimModules(CimSession cimSession, Uri resourceUri, string cimNamespace, string moduleNamePattern, bool onlyManifests, Cmdlet cmdlet, CancellationToken cancellationToken)
        {
            Func <CimModule, CimModule> selector        = null;
            WildcardPattern             wildcardPattern = new WildcardPattern(moduleNamePattern, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
            string optionValue          = WildcardPatternToDosWildcardParser.Parse(wildcardPattern);
            CimOperationOptions options = new CimOperationOptions {
                CancellationToken = new CancellationToken?(cancellationToken)
            };

            options.SetCustomOption("PS_ModuleNamePattern", optionValue, false);
            if (resourceUri != null)
            {
                options.ResourceUri = resourceUri;
            }
            if (string.IsNullOrEmpty(cimNamespace) && (resourceUri == null))
            {
                cimNamespace = "root/Microsoft/Windows/Powershellv3";
            }
            IEnumerable <CimModule> source = from cimInstance in cimSession.EnumerateInstances(cimNamespace, "PS_Module", options)
                                             select new CimModule(cimInstance) into cimModule
                                             where wildcardPattern.IsMatch(cimModule.ModuleName)
                                             select cimModule;

            if (!onlyManifests)
            {
                if (selector == null)
                {
                    selector = delegate(CimModule cimModule) {
                        cimModule.FetchAllModuleFiles(cimSession, cimNamespace, options);
                        return(cimModule);
                    };
                }
                source = source.Select <CimModule, CimModule>(selector);
            }
            return(EnumerateWithCatch <CimModule>(source, delegate(Exception exception) {
                ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception);
                if (!cmdlet.MyInvocation.ExpectingInput && (((-1 != errorRecord.FullyQualifiedErrorId.IndexOf("DiscoveryProviderNotFound", StringComparison.OrdinalIgnoreCase)) || cancellationToken.IsCancellationRequested) || ((exception is OperationCanceledException) || !cimSession.TestConnection())))
                {
                    cmdlet.ThrowTerminatingError(errorRecord);
                }
                cmdlet.WriteError(errorRecord);
            }));
        }
 protected internal override void BeginProcessingCore()
 {
     base.BeginProcessingCore();
     IEnumerable<PackageSource> sources;
     if (Scope == null)
     {
         sources = SourceService.AllSources;
     }
     else
     {
         IPackageSourceStore store = SourceService.GetSource(Scope.Value);
         sources = store.Sources;
     }
     if (!String.IsNullOrEmpty(Name))
     {
         WildcardPattern pattern = new WildcardPattern(Name);
         sources = sources.Where(s => pattern.IsMatch(s.Name));
     }
     WriteObject(sources, enumerateCollection: true);
 }
        protected override void ProcessRecord()
        {
            var repos = ConnectionFactory.GetRepositories(ConnectionParameters);
            if (Name == null || Name.Length == 0)
            {
                Name = new [] { "" };
            }
            foreach (var curName in Name)
            {
                var pattern = "*";
                if (!String.IsNullOrEmpty(curName))
                {
                    pattern = Exact.IsPresent ? curName : curName + "*";
                }
                var options = Exact.IsPresent ? WildcardOptions.None : WildcardOptions.IgnoreCase;
                WildcardPattern wildcard = new WildcardPattern(pattern, options);

                WriteObject(from rep in repos where wildcard.IsMatch(rep.Name) select rep, true);
            }
        }
Beispiel #29
0
        private ScriptInfo GetNextBuiltinScript()
        {
            ScriptInfo scriptInfo = null;

            if ((this.commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != SearchResolutionOptions.None)
            {
                if (this.matchingScript == null)
                {
                    Collection <string> collection = new Collection <string>();
                    WildcardPattern     pattern    = new WildcardPattern(this.commandName, WildcardOptions.IgnoreCase);
                    WildcardPattern     pattern2   = new WildcardPattern(this.commandName + ".ps1", WildcardOptions.IgnoreCase);
                    foreach (string str in this._context.CommandDiscovery.ScriptCache.Keys)
                    {
                        if (pattern.IsMatch(str) || pattern2.IsMatch(str))
                        {
                            collection.Add(str);
                        }
                    }
                    this.matchingScript = collection.GetEnumerator();
                }
                if (!this.matchingScript.MoveNext())
                {
                    this.currentState   = SearchState.StartSearchingForExternalCommands;
                    this.matchingScript = null;
                }
                else
                {
                    scriptInfo = this._context.CommandDiscovery.GetScriptInfo(this.matchingScript.Current);
                }
            }
            else
            {
                this.currentState = SearchState.StartSearchingForExternalCommands;
                scriptInfo        = this._context.CommandDiscovery.GetScriptInfo(this.commandName) ?? this._context.CommandDiscovery.GetScriptInfo(this.commandName + ".ps1");
            }
            if (scriptInfo != null)
            {
                CommandDiscovery.discoveryTracer.WriteLine("Script found: {0}", new object[] { scriptInfo.Name });
            }
            return(scriptInfo);
        }
Beispiel #30
0
        private ScriptInfo GetNextBuiltinScript()
        {
            ScriptInfo scriptInfo = (ScriptInfo)null;

            if ((this.commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != SearchResolutionOptions.None)
            {
                if (this.matchingScript == null)
                {
                    Collection <string> collection       = new Collection <string>();
                    WildcardPattern     wildcardPattern1 = new WildcardPattern(this.commandName, WildcardOptions.IgnoreCase);
                    WildcardPattern     wildcardPattern2 = new WildcardPattern(this.commandName + ".ps1", WildcardOptions.IgnoreCase);
                    foreach (string key in this._context.CommandDiscovery.ScriptCache.Keys)
                    {
                        if (wildcardPattern1.IsMatch(key) || wildcardPattern2.IsMatch(key))
                        {
                            collection.Add(key);
                        }
                    }
                    this.matchingScript = collection.GetEnumerator();
                }
                if (!this.matchingScript.MoveNext())
                {
                    this.currentState   = CommandSearcher.SearchState.BuiltinScriptResolution;
                    this.matchingScript = (IEnumerator <string>)null;
                }
                else
                {
                    scriptInfo = this._context.CommandDiscovery.GetScriptInfo(this.matchingScript.Current);
                }
            }
            else
            {
                this.currentState = CommandSearcher.SearchState.BuiltinScriptResolution;
                scriptInfo        = this._context.CommandDiscovery.GetScriptInfo(this.commandName) ?? this._context.CommandDiscovery.GetScriptInfo(this.commandName + ".ps1");
            }
            if (scriptInfo != null)
            {
                CommandDiscovery.discoveryTracer.WriteLine("Script found: {0}", (object)scriptInfo.Name);
            }
            return(scriptInfo);
        }
Beispiel #31
0
 private static void SetSnapInLoggingInformation(PSSnapInInfo psSnapInInfo, ModuleCmdletBase.ModuleLoggingGroupPolicyStatus status, IEnumerable <string> moduleOrSnapinNames)
 {
     if (((status & ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Enabled) != ModuleCmdletBase.ModuleLoggingGroupPolicyStatus.Undefined) && (moduleOrSnapinNames != null))
     {
         foreach (string str in moduleOrSnapinNames)
         {
             if (string.Equals(psSnapInInfo.Name, str, StringComparison.OrdinalIgnoreCase))
             {
                 psSnapInInfo.LogPipelineExecutionDetails = true;
             }
             else if (WildcardPattern.ContainsWildcardCharacters(str))
             {
                 WildcardPattern pattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
                 if (pattern.IsMatch(psSnapInInfo.Name))
                 {
                     psSnapInInfo.LogPipelineExecutionDetails = true;
                 }
             }
         }
     }
 }
Beispiel #32
0
        /// <summary>
        /// Convert the cacheItem to a PSClassInfo object.
        /// For this, we call Get-Module -List with module name.
        /// </summary>
        /// <param name="classNameMatcher">Wildcard pattern matcher for comparing class name.</param>
        /// <param name="modulePath">Path to the module where the class is defined.</param>
        /// <returns>Converted PSClassInfo object.</returns>
        private PSClassInfo CachedItemToPSClassInfo(WildcardPattern classNameMatcher, string modulePath)
        {
            foreach (var module in GetPSModuleInfo(modulePath))
            {
                var exportedTypes = module.GetExportedTypeDefinitions();

                ScriptBlockAst    ast     = null;
                TypeDefinitionAst typeAst = null;

                if (!_useWildCards)
                {
                    if (exportedTypes.TryGetValue(_className, out typeAst))
                    {
                        ast = typeAst.Parent.Parent as ScriptBlockAst;
                        if (ast != null)
                        {
                            return(ConvertToClassInfo(module, ast, typeAst));
                        }
                    }
                }
                else
                {
                    foreach (var exportedType in exportedTypes)
                    {
                        if (exportedType.Value != null &&
                            classNameMatcher.IsMatch(exportedType.Value.Name) &&
                            exportedType.Value.IsClass)
                        {
                            ast = exportedType.Value.Parent.Parent as ScriptBlockAst;
                            if (ast != null)
                            {
                                return(ConvertToClassInfo(module, ast, exportedType.Value));
                            }
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #33
0
 private Dictionary<Guid, PSSession> GetMatchingRunspacesByComputerName(bool writeobject, bool writeErrorOnNoMatch)
 {
     if ((this.computerNames == null) || (this.computerNames.Length == 0))
     {
         return this.GetAllRunspaces(writeobject, writeErrorOnNoMatch);
     }
     Dictionary<Guid, PSSession> dictionary = new Dictionary<Guid, PSSession>();
     List<PSSession> runspaces = base.RunspaceRepository.Runspaces;
     foreach (string str in this.computerNames)
     {
         WildcardPattern pattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
         bool flag = false;
         foreach (PSSession session in runspaces)
         {
             if (pattern.IsMatch(session.ComputerName))
             {
                 flag = true;
                 if (writeobject)
                 {
                     base.WriteObject(session);
                 }
                 else
                 {
                     try
                     {
                         dictionary.Add(session.InstanceId, session);
                     }
                     catch (ArgumentException)
                     {
                     }
                 }
             }
         }
         if (!flag && writeErrorOnNoMatch)
         {
             this.WriteInvalidArgumentError(PSRemotingErrorId.RemoteRunspaceNotAvailableForSpecifiedComputer, RemotingErrorIdStrings.RemoteRunspaceNotAvailableForSpecifiedComputer, str);
         }
     }
     return dictionary;
 }
Beispiel #34
0
        private CommandInfo GetNextAlias()
        {
            CommandInfo commandInfo = (CommandInfo)null;

            if ((this.commandResolutionOptions & SearchResolutionOptions.ResolveAliasPatterns) != SearchResolutionOptions.None)
            {
                if (this.matchingAlias == null)
                {
                    Collection <AliasInfo> collection      = new Collection <AliasInfo>();
                    WildcardPattern        wildcardPattern = new WildcardPattern(this.commandName, WildcardOptions.IgnoreCase);
                    foreach (KeyValuePair <string, AliasInfo> keyValuePair in (IEnumerable <KeyValuePair <string, AliasInfo> >) this._context.EngineSessionState.GetAliasTable())
                    {
                        if (wildcardPattern.IsMatch(keyValuePair.Key))
                        {
                            collection.Add(keyValuePair.Value);
                        }
                    }
                    this.matchingAlias = collection.GetEnumerator();
                }
                if (!this.matchingAlias.MoveNext())
                {
                    this.currentState  = CommandSearcher.SearchState.AliasResolution;
                    this.matchingAlias = (IEnumerator <AliasInfo>)null;
                }
                else
                {
                    commandInfo = (CommandInfo)this.matchingAlias.Current;
                }
            }
            else
            {
                this.currentState = CommandSearcher.SearchState.AliasResolution;
                commandInfo       = (CommandInfo)this._context.EngineSessionState.GetAlias(this.commandName);
            }
            if (commandInfo != null)
            {
                CommandDiscovery.discoveryTracer.WriteLine("Alias found: {0}  {1}", (object)commandInfo.Name, (object)commandInfo.Definition);
            }
            return(commandInfo);
        }
        /// <summary>
        /// Search help for a target.
        /// </summary>
        /// <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 collection of help info objects.</returns>
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            string target = helpRequest.Target;

            string wildcardpattern = GetWildCardPattern(target);

            HelpRequest searchHelpRequest = helpRequest.Clone();

            searchHelpRequest.Target = wildcardpattern;
            if (!this.CacheFullyLoaded)
            {
                IEnumerable <HelpInfo> result = DoSearchHelp(searchHelpRequest);
                if (result != null)
                {
                    foreach (HelpInfo helpInfoToReturn in result)
                    {
                        yield return(helpInfoToReturn);
                    }
                }
            }
            else
            {
                int             countOfHelpInfoObjectsFound = 0;
                WildcardPattern helpMatcher = WildcardPattern.Get(wildcardpattern, WildcardOptions.IgnoreCase);
                foreach (string key in _helpCache.Keys)
                {
                    if ((!searchOnlyContent && helpMatcher.IsMatch(key)) ||
                        (searchOnlyContent && ((HelpInfo)_helpCache[key]).MatchPatternInContent(helpMatcher)))
                    {
                        countOfHelpInfoObjectsFound++;
                        yield return((HelpInfo)_helpCache[key]);

                        if (helpRequest.MaxResults > 0 && countOfHelpInfoObjectsFound >= helpRequest.MaxResults)
                        {
                            yield break;
                        }
                    }
                }
            }
        }
Beispiel #36
0
        internal List <Job2> GetJobToStart(string definitionName, string definitionPath, string definitionType, Cmdlet cmdlet, bool writeErrorOnException)
        {
            List <Job2>     list    = new List <Job2>();
            WildcardPattern pattern = (definitionType != null) ? new WildcardPattern(definitionType, WildcardOptions.IgnoreCase) : null;

            lock (this._syncObject)
            {
                foreach (JobSourceAdapter adapter in this._sourceAdapters.Values)
                {
                    try
                    {
                        if (pattern != null)
                        {
                            string adapterName = this.GetAdapterName(adapter);
                            if (!pattern.IsMatch(adapterName))
                            {
                                continue;
                            }
                        }
                        Job2 item = adapter.NewJob(definitionName, definitionPath);
                        if (item != null)
                        {
                            list.Add(item);
                        }
                        if (pattern != null)
                        {
                            return(list);
                        }
                    }
                    catch (Exception exception)
                    {
                        this.Tracer.TraceException(exception);
                        CommandProcessorBase.CheckForSevereException(exception);
                        WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", adapter);
                    }
                }
                return(list);
            }
            return(list);
        }
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            string      target            = helpRequest.Target;
            string      wildCardPattern   = this.GetWildCardPattern(target);
            HelpRequest iteratorVariable2 = helpRequest.Clone();

            iteratorVariable2.Target = wildCardPattern;
            if (!this.CacheFullyLoaded)
            {
                IEnumerable <HelpInfo> iteratorVariable3 = this.DoSearchHelp(iteratorVariable2);
                if (iteratorVariable3 != null)
                {
                    foreach (HelpInfo iteratorVariable4 in iteratorVariable3)
                    {
                        yield return(iteratorVariable4);
                    }
                }
            }
            else
            {
                int             iteratorVariable5 = 0;
                WildcardPattern pattern           = new WildcardPattern(wildCardPattern, WildcardOptions.IgnoreCase);
                IEnumerator     enumerator        = this._helpCache.Keys.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    string current = (string)enumerator.Current;
                    if ((!searchOnlyContent && pattern.IsMatch(current)) || (searchOnlyContent && ((HelpInfo)this._helpCache[current]).MatchPatternInContent(pattern)))
                    {
                        iteratorVariable5++;
                        yield return((HelpInfo)this._helpCache[current]);

                        if ((helpRequest.MaxResults > 0) && (iteratorVariable5 >= helpRequest.MaxResults))
                        {
                            break;
                        }
                    }
                }
            }
        }
Beispiel #38
0
        internal bool IsMatch(WildcardPattern namePattern, PSSnapinQualifiedName psSnapinQualifiedName)
        {
            bool flag = false;

            if (psSnapinQualifiedName == null)
            {
                return(true);
            }
            if (namePattern == null)
            {
                if (string.Equals(this.Name, psSnapinQualifiedName.ShortName, StringComparison.OrdinalIgnoreCase) && this.IsPSSnapinNameMatch(psSnapinQualifiedName))
                {
                    flag = true;
                }
                return(flag);
            }
            if (namePattern.IsMatch(this.Name) && this.IsPSSnapinNameMatch(psSnapinQualifiedName))
            {
                flag = true;
            }
            return(flag);
        }
        /// <summary>
        /// Get a list of Provider operations in the case that the Actionstring input contains a wildcard
        /// </summary>
        private List<PSResourceProviderOperation> ProcessProviderOperationsWithWildCard(string actionString, Dictionary<string, string> resourceProvidersWithOperationsApi)
        {
            Dictionary<string, string> resourceProvidersToQuery = GetAzureProviderOperationCommand.FilterResourceProvidersToQueryForOperations(actionString, resourceProvidersWithOperationsApi);
            
            // Filter the list of all operation names to what matches the wildcard
            WildcardPattern wildcard = new WildcardPattern(actionString, WildcardOptions.IgnoreCase | WildcardOptions.Compiled);

            IList<ResourceIdentity> resourceidentities = new List<ResourceIdentity>();
            foreach (KeyValuePair<string, string> kvp in resourceProvidersToQuery)
            {
                ResourceIdentity identity = new ResourceIdentity()
                {
                    ResourceName = string.Empty,
                    ResourceType = "operations",
                    ResourceProviderNamespace = kvp.Key,
                    ResourceProviderApiVersion = kvp.Value
                };

                resourceidentities.Add(identity);
            }

            return this.ResourcesClient.ListPSProviderOperations(resourceidentities).Where(operation => wildcard.IsMatch(operation.OperationName)).ToList();
        }
Beispiel #40
0
        private CommandInfo GetNextFunction()
        {
            CommandInfo commandInfo = (CommandInfo)null;

            if ((this.commandResolutionOptions & SearchResolutionOptions.ResolveFunctionPatterns) != SearchResolutionOptions.None)
            {
                if (this.matchingFunctionEnumerator == null)
                {
                    Collection <CommandInfo> collection      = new Collection <CommandInfo>();
                    WildcardPattern          wildcardPattern = new WildcardPattern(this.commandName, WildcardOptions.IgnoreCase);
                    foreach (DictionaryEntry dictionaryEntry in this._context.EngineSessionState.GetFunctionTable())
                    {
                        if (wildcardPattern.IsMatch((string)dictionaryEntry.Key))
                        {
                            collection.Add((CommandInfo)dictionaryEntry.Value);
                        }
                    }
                    this.matchingFunctionEnumerator = collection.GetEnumerator();
                }
                if (!this.matchingFunctionEnumerator.MoveNext())
                {
                    this.currentState = CommandSearcher.SearchState.FunctionResolution;
                    this.matchingFunctionEnumerator = (IEnumerator <CommandInfo>)null;
                }
                else
                {
                    commandInfo = this.matchingFunctionEnumerator.Current;
                }
            }
            else
            {
                this.currentState = CommandSearcher.SearchState.FunctionResolution;
                commandInfo       = this.GetFunction(this.commandName);
            }
            return(commandInfo);
        }
Beispiel #41
0
        protected override void ProcessRecord()
        {
            if (this._name == null)
                this.WriteObject((object)VPMJob.GetAll(), true);
            else
            {

                foreach (string pattern in this._name)
                {
                    if (pattern == null)
                        this.WriteObject((object)VPMJob.GetAll(), true);
                    else
                    {
                        WildcardPattern wildcard = new WildcardPattern(pattern, WildcardOptions.Compiled | WildcardOptions.IgnoreCase);
                        foreach (VPMJob Job in (VPMJob.GetAll()))
                        {
                            if (wildcard.IsMatch(Job.Name))
                                WriteObject((object)Job, true);
                        }
                    }

                }
            }
        }
        protected bool TryGetHostEntries(HostsFile hostsFile, string name, int line, out ICollection<HostEntry> hostEntries)
        {
            hostEntries = hostsFile.Entries.ToList();

            if (line != -1 && MyInvocation.BoundParameters.Keys.Contains("Line"))
            {
                hostEntries = hostEntries.Where(e => e.Line == line).ToList();
                return hostEntries.Count == 1;
            }

            if (String.IsNullOrEmpty(name))
            {
                hostEntries = hostsFile.Entries.ToList();
                return true;
            }

            if (WildcardPattern.ContainsWildcardCharacters(name))
            {
                var pattern = new WildcardPattern(name, WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
                hostEntries = hostsFile.Entries.Where(e => pattern.IsMatch(e.Name)).ToList();
                return true;
            }
            else
            {
                hostEntries = hostsFile.Entries.Where(e => String.Equals(e.Name, name, StringComparison.InvariantCultureIgnoreCase)).ToList();

                if (hostEntries.Count == 0)
                {
                    WriteError(new ErrorRecord(new ItemNotFoundException(String.Format("Host entry '{0}' not found", name)),
                        "ItemNotFound", ErrorCategory.ObjectNotFound, name));
                    return false;
                }

                return true;
            }
        }
Beispiel #43
0
        public static bool IsValidByName(PackageEntryInfo packageEntry, NuGetSearchContext searchContext)
        {
            NuGetSearchTerm originalPsTerm = searchContext.SearchTerms == null ?
                                             null : searchContext.SearchTerms.Where(st => st.Term == NuGetSearchTerm.NuGetSearchTermType.OriginalPSPattern).FirstOrDefault();
            bool valid = true;

            if (originalPsTerm != null)
            {
                if (!String.IsNullOrWhiteSpace(originalPsTerm.Text) && SMA.WildcardPattern.ContainsWildcardCharacters(originalPsTerm.Text))
                {
                    // Applying the wildcard pattern matching
                    const SMA.WildcardOptions wildcardOptions = SMA.WildcardOptions.CultureInvariant | SMA.WildcardOptions.IgnoreCase;
                    var wildcardPattern = new SMA.WildcardPattern(originalPsTerm.Text, wildcardOptions);

                    valid = wildcardPattern.IsMatch(packageEntry.Id);
                }
                else if (!String.IsNullOrWhiteSpace(originalPsTerm.Text))
                {
                    valid = packageEntry.Id.IndexOf(originalPsTerm.Text, StringComparison.OrdinalIgnoreCase) > -1;
                }
            }

            return(valid);
        }
Beispiel #44
0
        private CmdletInfo GetNextCmdlet()
        {
            CmdletInfo result = (CmdletInfo)null;

            if (this.matchingCmdlet == null)
            {
                Collection <CmdletInfo> matchingCmdlets;
                if ((this.commandResolutionOptions & SearchResolutionOptions.CommandNameIsPattern) != SearchResolutionOptions.None)
                {
                    matchingCmdlets = new Collection <CmdletInfo>();
                    PSSnapinQualifiedName instance = PSSnapinQualifiedName.GetInstance(this.commandName);
                    if (instance == null)
                    {
                        return(result);
                    }
                    WildcardPattern wildcardPattern = new WildcardPattern(instance.ShortName, WildcardOptions.IgnoreCase);
                    Dictionary <string, List <CmdletInfo> > cmdletCache = this._context.EngineSessionState.CmdletCache;
                    while (true)
                    {
                        lock (cmdletCache)
                        {
                            foreach (List <CmdletInfo> cmdletInfoList in cmdletCache.Values)
                            {
                                foreach (CmdletInfo cmdletInfo in cmdletInfoList)
                                {
                                    if (wildcardPattern.IsMatch(cmdletInfo.Name) && (string.IsNullOrEmpty(instance.PSSnapInName) || instance.PSSnapInName.Equals(cmdletInfo.ModuleName, StringComparison.OrdinalIgnoreCase)))
                                    {
                                        matchingCmdlets.Add(cmdletInfo);
                                    }
                                }
                            }
                        }
                        if (cmdletCache != this._context.TopLevelSessionState.CmdletCache)
                        {
                            cmdletCache = this._context.TopLevelSessionState.CmdletCache;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                else
                {
                    matchingCmdlets = this._context.CommandDiscovery.GetCmdletInfo(this.commandName);
                    if (matchingCmdlets.Count > 1)
                    {
                        if ((this.commandResolutionOptions & SearchResolutionOptions.ReturnFirstDuplicateCmdletName) != SearchResolutionOptions.None)
                        {
                            this.matchingCmdlet = matchingCmdlets.GetEnumerator();
                            while (this.matchingCmdlet.MoveNext())
                            {
                                if (result == null)
                                {
                                    result = this.matchingCmdlet.Current;
                                }
                            }
                            return(this.traceResult(result));
                        }
                        if ((this.commandResolutionOptions & SearchResolutionOptions.AllowDuplicateCmdletNames) == SearchResolutionOptions.None)
                        {
                            throw this.NewAmbiguousCmdletName(this.commandName, matchingCmdlets);
                        }
                    }
                }
                this.matchingCmdlet = matchingCmdlets.GetEnumerator();
            }
            if (!this.matchingCmdlet.MoveNext())
            {
                this.currentState   = CommandSearcher.SearchState.CmdletResolution;
                this.matchingCmdlet = (IEnumerator <CmdletInfo>)null;
            }
            else
            {
                result = this.matchingCmdlet.Current;
            }
            return(this.traceResult(result));
        }
        /// <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;
                Hashtable hashtable = new Hashtable(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 (hashtable.ContainsKey(name))
                            {
                                continue;
                            }

                            hashtable.Add(name, null);

                            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 (hashtable.ContainsKey(name))
                            {
                                continue;
                            }

                            hashtable.Add(name, null);

                            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 (hashtable.ContainsKey(name))
                        {
                            continue;
                        }

                        hashtable.Add(name, null);

                        yield return(helpInfo);
                    }
                }
            }
        }
Beispiel #46
0
 internal Collection<PSSnapInInfo> GetPSSnapIn(string pattern, bool searchRegistry)
 {
     bool flag = WildcardPattern.ContainsWildcardCharacters(pattern);
     if (!flag)
     {
         PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern);
     }
     Collection<PSSnapInInfo> collection = searchRegistry ? PSSnapInReader.ReadAll() : this.PSSnapIns;
     Collection<PSSnapInInfo> collection2 = new Collection<PSSnapInInfo>();
     if (collection != null)
     {
         if (!flag)
         {
             foreach (PSSnapInInfo info in collection)
             {
                 if (string.Equals(info.Name, pattern, StringComparison.OrdinalIgnoreCase))
                 {
                     collection2.Add(info);
                 }
             }
             return collection2;
         }
         WildcardPattern pattern2 = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
         foreach (PSSnapInInfo info2 in collection)
         {
             if (pattern2.IsMatch(info2.Name))
             {
                 collection2.Add(info2);
             }
         }
     }
     return collection2;
 }
Beispiel #47
0
 internal bool IsMatchingType(PSTypeName psTypeName)
 {
     Type fromType = psTypeName.Type;
     if (fromType != null)
     {
         bool flag = LanguagePrimitives.FigureConversion(typeof(object), this.ParameterType).Rank >= ConversionRank.AssignableS2A;
         if (fromType.Equals(typeof(object)))
         {
             return flag;
         }
         if (flag)
         {
             return ((psTypeName.Type != null) && psTypeName.Type.Equals(typeof(object)));
         }
         LanguagePrimitives.ConversionData data = LanguagePrimitives.FigureConversion(fromType, this.ParameterType);
         return ((data != null) && (data.Rank >= ConversionRank.NumericImplicitS2A));
     }
     WildcardPattern pattern = new WildcardPattern("*" + (psTypeName.Name ?? ""), WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase);
     if (pattern.IsMatch(this.ParameterType.FullName))
     {
         return true;
     }
     if (this.ParameterType.IsArray && pattern.IsMatch(this.ParameterType.GetElementType().FullName))
     {
         return true;
     }
     if (this.Attributes != null)
     {
         PSTypeNameAttribute attribute = this.Attributes.OfType<PSTypeNameAttribute>().FirstOrDefault<PSTypeNameAttribute>();
         if ((attribute != null) && pattern.IsMatch(attribute.PSTypeName))
         {
             return true;
         }
     }
     return false;
 }
 private static void GetCommandletsFromAssembly(Assembly assembly, WildcardPattern wildcard)
 {
     foreach (Type type in assembly.GetTypes())
     {
         if (type.GetCustomAttributes(typeof(CmdletAttribute), true).Length > 0 &&
             wildcard.IsMatch(type.FullName))
         {
             var attribute = (CmdletAttribute)(type.GetCustomAttributes(typeof(CmdletAttribute), true)[0]);
             Commandlets.Add(new CmdletConfigurationEntry(attribute.VerbName + "-" + attribute.NounName, type, "..\\Console\\Assets\\Cognifide.PowerShell-Help.xml"));
         }
     }
 }
Beispiel #49
0
        internal List<Process> FindProcessesByNames()
        {
            List<Process> foundProcesses = new List<Process>();

            if (_processNames == null)
            {
                return new List<Process>(AllProcesses);
            }
            else
            {
                foreach (string name in _processNames)
                {
                    WildcardPattern pattern = new WildcardPattern(name, WildcardOptions.IgnoreCase);
                    bool bFound = false;

                    foreach (Process process in AllProcesses)
                    {
                        if (pattern.IsMatch(GetProcessName(process)))
                        {
                            bFound = true;
                            foundProcesses.Add(process);
                        }
                    }

                    if (!bFound && !WildcardPattern.ContainsWildcardCharacters(name))
                    {
                        WriteError(new ErrorRecord(new Exception("Can't find process for name: " + name), "", ErrorCategory.ObjectNotFound, name));
                    }
                }
            }
            return foundProcesses;
        }
Beispiel #50
0
		private void RetrieveMatchingProcessesByProcessName()
		{
			if (this.processNames != null)
			{
				string[] strArrays = this.processNames;
				for (int i = 0; i < (int)strArrays.Length; i++)
				{
					string str = strArrays[i];
					WildcardPattern wildcardPattern = new WildcardPattern(str, WildcardOptions.IgnoreCase);
					bool flag = false;
					Process[] allProcesses = this.AllProcesses;
					for (int j = 0; j < (int)allProcesses.Length; j++)
					{
						Process process = allProcesses[j];
						if (wildcardPattern.IsMatch(ProcessBaseCommand.SafeGetProcessName(process)))
						{
							flag = true;
							this.AddIdempotent(process);
						}
					}
					if (!flag && !WildcardPattern.ContainsWildcardCharacters(str))
					{
						this.WriteNonTerminatingError(str, 0, str, null, ProcessResources.NoProcessFoundForGivenName, "NoProcessFoundForGivenName", ErrorCategory.ObjectNotFound);
					}
				}
				return;
			}
			else
			{
				this._matchingProcesses = new List<Process>(this.AllProcesses);
				return;
			}
		}
Beispiel #51
0
        /// <summary>
        /// Resets the current working drive and directory to the first
        /// entry on the working directory stack and removes that entry
        /// from the stack.
        /// </summary>
        /// <param name="stackName">
        /// The ID of the stack to pop the location from. If it is null or
        /// empty the default stack is used.
        /// </param>
        /// <returns>
        /// A PathInfo object representing the location that was popped
        /// from the location stack and set as the new location.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If the path on the stack does not exist, is not a container, or
        /// resolved to multiple containers.
        /// or
        /// If <paramref name="stackName"/> contains wildcard characters and resolves
        /// to multiple location stacks.
        /// or
        /// A stack was not found with the specified name.
        /// </exception>
        /// <exception cref="ProviderNotFoundException">
        /// If the path on the stack refers to a provider that does not exist.
        /// </exception>
        /// <exception cref="DriveNotFoundException">
        /// If the path on the stack refers to a drive that does not exist.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with the path on the stack threw an
        /// exception.
        /// </exception>
        internal PathInfo PopLocation(string stackName)
        {
            if (String.IsNullOrEmpty(stackName))
            {
                stackName = _defaultStackName;
            }

            if (WildcardPattern.ContainsWildcardCharacters(stackName))
            {
                // Need to glob the stack name, but it can only glob to a single.
                bool haveMatch = false;

                WildcardPattern stackNamePattern =
                    WildcardPattern.Get(stackName, WildcardOptions.IgnoreCase);

                foreach (string key in _workingLocationStack.Keys)
                {
                    if (stackNamePattern.IsMatch(key))
                    {
                        if (haveMatch)
                        {
                            throw
                                PSTraceSource.NewArgumentException(
                                    "stackName",
                                    SessionStateStrings.StackNameResolvedToMultiple,
                                    stackName);
                        }

                        haveMatch = true;
                        stackName = key;
                    }
                }
            }

            PathInfo result = CurrentLocation;

            try
            {
                Stack <PathInfo> locationStack = null;
                if (!_workingLocationStack.TryGetValue(stackName, out locationStack))
                {
                    if (!string.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase))
                    {
                        throw
                            PSTraceSource.NewArgumentException(
                                "stackName",
                                SessionStateStrings.StackNotFound,
                                stackName);
                    }

                    return(null);
                }

                PathInfo poppedWorkingDirectory = locationStack.Pop();

                Dbg.Diagnostics.Assert(
                    poppedWorkingDirectory != null,
                    "All items in the workingLocationStack should be " +
                    "of type PathInfo");

                string newPath =
                    LocationGlobber.GetMshQualifiedPath(
                        WildcardPattern.Escape(poppedWorkingDirectory.Path),
                        poppedWorkingDirectory.GetDrive());

                result = SetLocation(newPath);

                if (locationStack.Count == 0 &&
                    !String.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase))
                {
                    // Remove the stack from the stack list if it
                    // no longer contains any paths.
                    _workingLocationStack.Remove(stackName);
                }
            }
            catch (InvalidOperationException)
            {
                // This is a no-op. We stay with the current working
                // directory.
            }

            return(result);
        }
 private PSSession GetSessionByName(string name)
 {
     WildcardPattern pattern = new WildcardPattern(name, WildcardOptions.IgnoreCase);
     foreach (PSSession session in base.RunspaceRepository.Runspaces)
     {
         if (pattern.IsMatch(session.Name))
         {
             return session;
         }
     }
     return null;
 }
        /// <summary>
        /// Invoke command Get-DscResource with resource name to find the resource.
        /// When found add them to the enumerator. If we have already got it, return the next resource.
        /// </summary>
        /// <returns>Next DscResource Info object or null if none are found.</returns>
        private DscResourceInfo GetNextDscResource()
        {
            var ps = PowerShell.Create(RunspaceMode.CurrentRunspace).AddCommand("Get-DscResource");

            WildcardPattern resourceMatcher = WildcardPattern.Get(_resourceName, WildcardOptions.IgnoreCase);

            if (_matchingResourceList == null)
            {
                Collection <PSObject> psObjs = ps.Invoke();

                _matchingResourceList = new Collection <DscResourceInfo>();

                bool matchFound = false;

                foreach (dynamic resource in psObjs)
                {
                    if (resource.Name != null)
                    {
                        string resourceName = resource.Name;

                        if (resourceMatcher.IsMatch(resourceName))
                        {
                            DscResourceInfo resourceInfo = new DscResourceInfo(resourceName,
                                                                               resource.ResourceType,
                                                                               resource.Path,
                                                                               resource.ParentPath,
                                                                               _context
                                                                               );

                            resourceInfo.FriendlyName = resource.FriendlyName;

                            resourceInfo.CompanyName = resource.CompanyName;

                            PSModuleInfo psMod = resource.Module as PSModuleInfo;

                            if (psMod != null)
                            {
                                resourceInfo.Module = psMod;
                            }

                            if (resource.ImplementedAs != null)
                            {
                                ImplementedAsType impType;
                                if (Enum.TryParse <ImplementedAsType>(resource.ImplementedAs.ToString(), out impType))
                                {
                                    resourceInfo.ImplementedAs = impType;
                                }
                            }

                            var properties = resource.Properties as IList;

                            if (properties != null)
                            {
                                List <DscResourcePropertyInfo> propertyList = new List <DscResourcePropertyInfo>();

                                foreach (dynamic prop in properties)
                                {
                                    DscResourcePropertyInfo propInfo = new DscResourcePropertyInfo();
                                    propInfo.Name         = prop.Name;
                                    propInfo.PropertyType = prop.PropertyType;
                                    propInfo.UpdateValues(prop.Values);

                                    propertyList.Add(propInfo);
                                }

                                resourceInfo.UpdateProperties(propertyList);
                            }

                            _matchingResourceList.Add(resourceInfo);

                            matchFound = true;
                        }
                    }
                }

                if (matchFound)
                {
                    _matchingResource = _matchingResourceList.GetEnumerator();
                }
                else
                {
                    return(null);
                }
            }

            if (!_matchingResource.MoveNext())
            {
                _matchingResource = null;
            }
            else
            {
                return(_matchingResource.Current);
            }

            return(null);
        }
Beispiel #54
0
        internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
        {
            if (!searchOnlyContent)
            {
                string    target            = helpRequest.Target;
                string    pattern           = target;
                Hashtable iteratorVariable2 = new Hashtable(StringComparer.OrdinalIgnoreCase);
                if (!WildcardPattern.ContainsWildcardCharacters(target))
                {
                    pattern = pattern + "*";
                }
                WildcardPattern iteratorVariable3          = new WildcardPattern(pattern, WildcardOptions.IgnoreCase);
                IDictionary <string, AliasInfo> aliasTable = this._sessionState.Internal.GetAliasTable();
                foreach (string iteratorVariable5 in aliasTable.Keys)
                {
                    if (iteratorVariable3.IsMatch(iteratorVariable5))
                    {
                        HelpRequest iteratorVariable6 = helpRequest.Clone();
                        iteratorVariable6.Target = iteratorVariable5;
                        foreach (HelpInfo iteratorVariable7 in this.ExactMatchHelp(iteratorVariable6))
                        {
                            if (!Match(iteratorVariable7, helpRequest) || iteratorVariable2.ContainsKey(iteratorVariable5))
                            {
                                continue;
                            }
                            iteratorVariable2.Add(iteratorVariable5, null);
                            yield return(iteratorVariable7);
                        }
                    }
                }
                CommandSearcher iteratorVariable8 = new CommandSearcher(pattern, SearchResolutionOptions.ResolveAliasPatterns, CommandTypes.Alias, this._context);
                while (iteratorVariable8.MoveNext())
                {
                    CommandInfo current = iteratorVariable8.Current;
                    if (this._context.CurrentPipelineStopping)
                    {
                        goto Label_0423;
                    }
                    AliasInfo iteratorVariable10 = current as AliasInfo;
                    if (iteratorVariable10 != null)
                    {
                        string      name = iteratorVariable10.Name;
                        HelpRequest iteratorVariable12 = helpRequest.Clone();
                        iteratorVariable12.Target = name;
                        foreach (HelpInfo iteratorVariable13 in this.ExactMatchHelp(iteratorVariable12))
                        {
                            if (!Match(iteratorVariable13, helpRequest) || iteratorVariable2.ContainsKey(name))
                            {
                                continue;
                            }
                            iteratorVariable2.Add(name, null);
                            yield return(iteratorVariable13);
                        }
                    }
                }
                foreach (CommandInfo iteratorVariable14 in ModuleUtils.GetMatchingCommands(pattern, this._context, helpRequest.CommandOrigin, false))
                {
                    if (this._context.CurrentPipelineStopping)
                    {
                        break;
                    }
                    AliasInfo aliasInfo = iteratorVariable14 as AliasInfo;
                    if (aliasInfo != null)
                    {
                        string   key      = aliasInfo.Name;
                        HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(aliasInfo);
                        if (!iteratorVariable2.ContainsKey(key))
                        {
                            iteratorVariable2.Add(key, null);
                            yield return(helpInfo);
                        }
                    }
                }
            }
Label_0423:
            yield break;
        }