internal bool IsMatch(string providerName) { PSSnapinQualifiedName psSnapinQualifiedName = PSSnapinQualifiedName.GetInstance(providerName); WildcardPattern namePattern = null; if (psSnapinQualifiedName != null && WildcardPattern.ContainsWildcardCharacters(psSnapinQualifiedName.ShortName)) { namePattern = WildcardPattern.Get(psSnapinQualifiedName.ShortName, WildcardOptions.IgnoreCase); } return IsMatch(namePattern, psSnapinQualifiedName); }
/// <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()); }
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)); }
/// <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; } } } } }
/// <summary> /// Constructs a collection of WildcardPatterns for the specified /// string collection. /// </summary> /// <param name="globPatterns"> /// The string patterns to construct the WildcardPatterns for. /// </param> /// <param name="options"> /// The options to create the WildcardPatterns with. /// </param> /// <returns> /// A collection of WildcardPatterns that represent the string patterns /// that were passed. /// </returns> internal static Collection <WildcardPattern> CreateWildcardsFromStrings( IEnumerable <string> globPatterns, WildcardOptions options) { Collection <WildcardPattern> result = new Collection <WildcardPattern>(); if (globPatterns != null) { // Loop through the patterns and construct a wildcard pattern for each one foreach (string pattern in globPatterns) { if (!string.IsNullOrEmpty(pattern)) { result.Add( WildcardPattern.Get( pattern, options)); } } } return(result); }
/// <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); }
/// <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); } } } }
private static IEnumerable <CimModule> GetCimModules( CimSession cimSession, Uri resourceUri, string cimNamespace, string moduleNamePattern, bool onlyManifests, Cmdlet cmdlet, CancellationToken cancellationToken) { Dbg.Assert(cimSession != null, "Caller should verify cimSession != null"); Dbg.Assert(moduleNamePattern != null, "Caller should verify that moduleNamePattern != null"); const WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; var wildcardPattern = WildcardPattern.Get(moduleNamePattern, wildcardOptions); string dosWildcard = WildcardPatternToDosWildcardParser.Parse(wildcardPattern); var options = new CimOperationOptions { CancellationToken = cancellationToken }; options.SetCustomOption("PS_ModuleNamePattern", dosWildcard, mustComply: false); if (resourceUri != null) { options.ResourceUri = resourceUri; } if (string.IsNullOrEmpty(cimNamespace) && (resourceUri == null)) { cimNamespace = DiscoveryProviderNamespace; } // TODO/FIXME: ETW for method invocation IEnumerable <CimInstance> syncResults = cimSession.EnumerateInstances( cimNamespace, DiscoveryProviderModuleClass, options); // TODO/FIXME: ETW for method results IEnumerable <CimModule> cimModules = syncResults .Select(cimInstance => new CimModule(cimInstance)) .Where(cimModule => wildcardPattern.IsMatch(cimModule.ModuleName)); if (!onlyManifests) { cimModules = cimModules.Select( delegate(CimModule cimModule) { cimModule.FetchAllModuleFiles(cimSession, cimNamespace, options); return(cimModule); }); } return(EnumerateWithCatch( cimModules, delegate(Exception exception) { ErrorRecord errorRecord = GetErrorRecordForRemoteDiscoveryProvider(exception); if (!cmdlet.MyInvocation.ExpectingInput) { if (((-1) != errorRecord.FullyQualifiedErrorId.IndexOf(DiscoveryProviderNotFoundErrorId, StringComparison.OrdinalIgnoreCase)) || (cancellationToken.IsCancellationRequested || (exception is OperationCanceledException)) || (!cimSession.TestConnection())) { cmdlet.ThrowTerminatingError(errorRecord); } } cmdlet.WriteError(errorRecord); })); }
/// <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); }
internal static ScriptAnalysis Analyze(string path, ExecutionContext context) { ModuleIntrinsics.Tracer.WriteLine("Analyzing path: {0}", path); try { if (Utils.PathIsUnc(path) && (context.CurrentCommandProcessor.CommandRuntime != null)) { ProgressRecord analysisProgress = new ProgressRecord(0, Modules.ScriptAnalysisPreparing, string.Format(CultureInfo.InvariantCulture, Modules.ScriptAnalysisModule, path)); analysisProgress.RecordType = ProgressRecordType.Processing; // Write the progress using a static source ID so that all // analysis messages get single-threaded in the progress pane (rather than nesting). context.CurrentCommandProcessor.CommandRuntime.WriteProgress(typeof(ScriptAnalysis).FullName.GetHashCode(), analysisProgress); } } catch (InvalidOperationException) { // This may be called when we are not allowed to write progress, // So eat the invalid operation } string scriptContent = ReadScript(path); ParseError[] errors; var moduleAst = (new Parser()).Parse(path, scriptContent, null, out errors, ParseMode.ModuleAnalysis); // Don't bother analyzing if there are syntax errors (we don't do semantic analysis which would // detect other errors that we also might choose to ignore, but it's slower.) if (errors.Length > 0) { return(null); } ExportVisitor exportVisitor = new ExportVisitor(forCompletion: false); moduleAst.Visit(exportVisitor); var result = new ScriptAnalysis { DiscoveredClasses = exportVisitor.DiscoveredClasses, DiscoveredExports = exportVisitor.DiscoveredExports, DiscoveredAliases = new Dictionary <string, string>(), DiscoveredModules = exportVisitor.DiscoveredModules, DiscoveredCommandFilters = exportVisitor.DiscoveredCommandFilters, AddsSelfToPath = exportVisitor.AddsSelfToPath }; if (result.DiscoveredCommandFilters.Count == 0) { result.DiscoveredCommandFilters.Add("*"); } else { // Post-process aliases, as they are not exported by default List <WildcardPattern> patterns = new List <WildcardPattern>(); foreach (string discoveredCommandFilter in result.DiscoveredCommandFilters) { patterns.Add(WildcardPattern.Get(discoveredCommandFilter, WildcardOptions.IgnoreCase)); } foreach (var pair in exportVisitor.DiscoveredAliases) { string discoveredAlias = pair.Key; if (SessionStateUtilities.MatchesAnyWildcardPattern(discoveredAlias, patterns, defaultValue: false)) { result.DiscoveredAliases[discoveredAlias] = pair.Value; } } } return(result); }
internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { string target = helpRequest.Target; string pattern = target; int countOfHelpInfoObjectsFound = 0; // this will be used only when searchOnlyContent == true WildcardPattern wildCardPattern = null; if ((!searchOnlyContent) && (!WildcardPattern.ContainsWildcardCharacters(target))) { // Search all the about conceptual topics. This pattern // makes about topics discoverable without actually // using the word "about_" as in "get-help while". pattern = "*" + pattern + "*"; } if (searchOnlyContent) { string searchTarget = helpRequest.Target; if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target)) { searchTarget = "*" + searchTarget + "*"; } wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); // search all about_* topics pattern = "*"; } pattern += ".help.txt"; Collection <String> files = MUIFileSearcher.SearchFiles(pattern, GetExtendedSearchPaths()); var matchedFilesToRemove = FilterToLatestModuleVersion(files); if (files == null) { yield break; } foreach (string file in files) { if (matchedFilesToRemove.Contains(file)) { continue; } // Check whether the file is already loaded if (!_helpFiles.ContainsKey(file)) { try { LoadHelpFile(file); } catch (IOException ioException) { ReportHelpFileError(ioException, helpRequest.Target, file); } catch (System.Security.SecurityException securityException) { ReportHelpFileError(securityException, helpRequest.Target, file); } } HelpFileHelpInfo helpInfo = GetCache(file) as HelpFileHelpInfo; if (helpInfo != null) { if (searchOnlyContent) { if (!helpInfo.MatchPatternInContent(wildCardPattern)) { continue; } } countOfHelpInfoObjectsFound++; yield return(helpInfo); if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0) { yield break; } } } }
/// <summary> /// Search for provider help based on a search 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></returns> internal override IEnumerable <HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { int countOfHelpInfoObjectsFound = 0; string target = helpRequest.Target; string pattern = target; // this will be used only when searchOnlyContent == true WildcardPattern wildCardPattern = null; bool decoratedSearch = !WildcardPattern.ContainsWildcardCharacters(target); if (!searchOnlyContent) { if (decoratedSearch) { pattern += "*"; } } else { string searchTarget = helpRequest.Target; if (decoratedSearch) { searchTarget = "*" + helpRequest.Target + "*"; } wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); // search in all providers pattern = "*"; } PSSnapinQualifiedName snapinQualifiedNameForPattern = PSSnapinQualifiedName.GetInstance(pattern); if (null == snapinQualifiedNameForPattern) { yield break; } foreach (ProviderInfo providerInfo in _sessionState.Provider.GetAll()) { if (providerInfo.IsMatch(pattern)) { try { LoadHelpFile(providerInfo); } catch (IOException ioException) { if (!decoratedSearch) { ReportHelpFileError(ioException, providerInfo.Name, providerInfo.HelpFile); } } catch (System.Security.SecurityException securityException) { if (!decoratedSearch) { ReportHelpFileError(securityException, providerInfo.Name, providerInfo.HelpFile); } } catch (XmlException xmlException) { if (!decoratedSearch) { ReportHelpFileError(xmlException, providerInfo.Name, providerInfo.HelpFile); } } HelpInfo helpInfo = GetCache(providerInfo.PSSnapInName + "\\" + providerInfo.Name); if (helpInfo != null) { if (searchOnlyContent) { // ignore help objects that do not have pattern in its help // content. if (!helpInfo.MatchPatternInContent(wildCardPattern)) { continue; } } countOfHelpInfoObjectsFound++; yield return(helpInfo); if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0) { yield break; } } } } }