// 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; }
internal override List<IUiElement> FilterElements(SingleControlSearcherData controlSearcherData, List<IUiElement> initialCollection) { const WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.Compiled; var wildcardName = new WildcardPattern(controlSearcherData.Name ?? "*", options); var wildcardValue = new WildcardPattern(controlSearcherData.Value ?? "*", options); foreach (IUiElement element in initialCollection) { if (element.IsMatchWildcardPattern(ResultCollection, wildcardName, element.GetCurrent().Name)) continue; if (element.IsMatchWildcardPattern(ResultCollection, wildcardName, element.GetCurrent().AutomationId)) continue; if (element.IsMatchWildcardPattern(ResultCollection, wildcardName, element.GetCurrent().ClassName)) continue; try { string elementValue = element.GetCurrentPattern<IValuePattern>(classic.ValuePattern.Pattern).Current.Value; if (element.IsMatchWildcardPattern(ResultCollection, wildcardName, elementValue)) continue; if (element.IsMatchWildcardPattern(ResultCollection, wildcardValue, elementValue)) continue; } catch { } } return ResultCollection; }
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; }
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(); }
/// <summary> /// Get a list of Provider operations in the case that the Actionstring input contains a wildcard /// </summary> private List<PSResourceProviderOperation> ProcessProviderOperationsWithWildCard(string actionString) { // Filter the list of all operation names to what matches the wildcard WildcardPattern wildcard = new WildcardPattern(actionString, WildcardOptions.IgnoreCase | WildcardOptions.Compiled); List<ProviderOperationsMetadata> providers = new List<ProviderOperationsMetadata>(); string nonWildCardPrefix = GetAzureProviderOperationCommand.GetNonWildcardPrefix(actionString); if (string.IsNullOrWhiteSpace(nonWildCardPrefix)) { // 'Get-AzureProviderOperation *' or 'Get-AzureProviderOperation */virtualmachines/*' // get operations for all providers providers.AddRange(this.ResourcesClient.ListProviderOperationsMetadata()); } else { // Some string exists before the wild card character - potentially the full name of the provider. string providerFullName = GetAzureProviderOperationCommand.GetResourceProviderFullName(nonWildCardPrefix); if (!string.IsNullOrWhiteSpace(providerFullName)) { // we have the full name of the provider. 'Get-AzureProviderOperation Microsoft.Sql/servers/*' // only query for that provider providers.Add(this.ResourcesClient.GetProviderOperationsMetadata(providerFullName)); } else { // We have only a partial name of the provider, say Microsoft.*/* or Microsoft.*/*/read. // query for all providers and then do prefix match on the operations providers.AddRange(this.ResourcesClient.ListProviderOperationsMetadata()); } } return providers.SelectMany(p => GetPSOperationsFromProviderOperationsMetadata(p)).Where(operation => wildcard.IsMatch(operation.Operation)).ToList(); }
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); } }
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(); }
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(); }
public static void Parse(WildcardPattern pattern, WildcardPatternParser parser) { parser.BeginWildcardPattern(pattern); bool flag = false; bool flag2 = false; bool flag3 = false; StringBuilder builder = null; StringBuilder builder2 = null; foreach (char ch in pattern.Pattern) { if (flag3) { if (((ch == ']') && !flag2) && !flag) { flag3 = false; parser.AppendBracketExpression(builder.ToString(), builder2.ToString(), pattern.Pattern); builder = null; builder2 = null; } else if ((ch != '`') || flag) { builder.Append(ch); builder2.Append(((ch == '-') && !flag) ? '-' : ' '); } flag2 = false; } else if ((ch == '*') && !flag) { parser.AppendAsterix(); } else if ((ch == '?') && !flag) { parser.AppendQuestionMark(); } else if ((ch == '[') && !flag) { flag3 = true; builder = new StringBuilder(); builder2 = new StringBuilder(); flag2 = true; } else if ((ch != '`') || flag) { parser.AppendLiteralCharacter(ch); } flag = (ch == '`') && !flag; } if (flag3) { throw NewWildcardPatternException(pattern.Pattern); } if (flag && !pattern.Pattern.Equals("`", StringComparison.Ordinal)) { parser.AppendLiteralCharacter(pattern.Pattern[pattern.Pattern.Length - 1]); } parser.EndWildcardPattern(); }
protected static WildcardPattern GetWildcardPattern(string name) { if (String.IsNullOrEmpty(name)) { name = "*"; } const WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.Compiled; var wildcard = new WildcardPattern(name, options); return wildcard; }
protected override void EndProcessing() { try { Predicate<string> IsMatch; // name provided? if (!String.IsNullOrEmpty(this.Name)) { // Need an explicit wildcard match? if (WildcardPattern.ContainsWildcardCharacters(this.Name)) { // yes, the user provided some wildcard characters var pattern = new WildcardPattern(this.Name, WildcardOptions.IgnoreCase); // use method group (delegate inference) for pattern match IsMatch = pattern.IsMatch; } else { // use lambda for implicit wildcard matching - the user most likely // is not looking for an exact match, so treat it as a substring search. IsMatch = (name => (name.IndexOf(this.Name, 0, StringComparison.OrdinalIgnoreCase) != -1)); } } else { // return all IsMatch = delegate { return true; }; } // Dump out installed data providers available to .NET foreach (DataRow factory in DbProviderFactories.GetFactoryClasses().Rows) { var name = (string) factory["InvariantName"]; var displayName = (string) factory["Name"]; var description = (string) factory["Description"]; if (IsMatch(name)) { var factoryInfo = new PSObject(); factoryInfo.Properties.Add(new PSNoteProperty("ProviderName", name)); factoryInfo.Properties.Add(new PSNoteProperty("DisplayName", displayName)); factoryInfo.Properties.Add(new PSNoteProperty("Description", description)); WriteObject(factoryInfo); } } } finally { base.EndProcessing(); } }
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; }
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); }
protected internal Collection<PSSnapInInfo> GetSnapIns(string pattern) { if (this.Runspace != null) { if (pattern != null) { return this.Runspace.ConsoleInfo.GetPSSnapIn(pattern, this._shouldGetAll); } return this.Runspace.ConsoleInfo.PSSnapIns; } WildcardPattern pattern2 = null; if (!string.IsNullOrEmpty(pattern)) { if (!WildcardPattern.ContainsWildcardCharacters(pattern)) { PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(pattern); } pattern2 = new WildcardPattern(pattern, WildcardOptions.IgnoreCase); } Collection<PSSnapInInfo> collection = new Collection<PSSnapInInfo>(); if (this._shouldGetAll) { foreach (PSSnapInInfo info in PSSnapInReader.ReadAll()) { if ((pattern2 == null) || pattern2.IsMatch(info.Name)) { collection.Add(info); } } return collection; } List<CmdletInfo> cmdlets = base.InvokeCommand.GetCmdlets(); Dictionary<PSSnapInInfo, bool> dictionary = new Dictionary<PSSnapInInfo, bool>(); foreach (CmdletInfo info2 in cmdlets) { PSSnapInInfo pSSnapIn = info2.PSSnapIn; if ((pSSnapIn != null) && !dictionary.ContainsKey(pSSnapIn)) { dictionary.Add(pSSnapIn, true); } } foreach (PSSnapInInfo info4 in dictionary.Keys) { if ((pattern2 == null) || pattern2.IsMatch(info4.Name)) { collection.Add(info4); } } return collection; }
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)); } } } }
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))); } }
/// <summary> /// Creates a list of property name wildcard patterns. /// </summary> protected override void BeginProcessing() { var count = this.Property.Count(); if (0 < count) { this.propertyPatterns = new List<WildcardPattern>(count); foreach (var property in this.Property) { var pattern = new WildcardPattern(property, WildcardOptions.Compiled | WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); this.propertyPatterns.Add(pattern); } } base.BeginProcessing(); }
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)); } }
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; }
protected override void ProcessRecord() { var cmisPath = new CmisPath(Path); var navigation = new CmisNavigation(CmisSession, WorkingFolder); ICmisObject obj = null; try { obj = navigation.Get(cmisPath); } catch (CmisBaseException e) { ThrowTerminatingError(new ErrorRecord(e, "GetObjectFailed", ErrorCategory.ResourceUnavailable, Path)); return; } var nameIsEmpty = String.IsNullOrEmpty(Name); if (!(obj is IFolder) || (!cmisPath.HasTrailingSlash() && nameIsEmpty && RecursionDepth < 1)) { WriteObject(obj); return; } WildcardPattern wildcard = new WildcardPattern("*"); if (!nameIsEmpty) { wildcard = Exact.IsPresent ? new WildcardPattern(Name) : new WildcardPattern(Name + "*", WildcardOptions.IgnoreCase); } int depth = RecursionDepth == 0 ? 1 : RecursionDepth; //otherwise we want the descendants of the folder var folder = obj as IFolder; IList<ITree<IFileableCmisObject>> descendants; try { descendants = folder.GetDescendants(depth); } catch (CmisBaseException e) { ThrowTerminatingError(new ErrorRecord(e, "GetDescendatnsFailed", ErrorCategory.ResourceUnavailable, Path)); return; } WriteTreeList(descendants, wildcard); }
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); } }
protected static WildcardPattern PrepareWildcardPattern(string pattern) { WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.Compiled; WildcardPattern wildcard = null; if (!String.IsNullOrEmpty(pattern)) { wildcard = new WildcardPattern(pattern, options); } else { wildcard = new WildcardPattern("*", options); } return wildcard; }
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; }
internal override void Execute() { var cmdlet = (GetTmxCommonDataItemCommand)Cmdlet; try { // cmdlet.WriteObject(ClientSettings.Instance.CommonData.Data[cmdlet.Key]); const WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.Compiled; var pattern = new WildcardPattern(cmdlet.Key, options); ClientSettings.Instance.CommonData.Data.Keys // .Where(key => pattern.IsMatch(key)) .Where(pattern.IsMatch) .ToList() .ForEach(key => cmdlet.WriteObject(ClientSettings.Instance.CommonData.Data[key])); } catch (Exception e) { throw new Exception("Failed to get value with key '" + cmdlet.Key + "'. " + e.Message); } }
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; }
internal static bool ConditionSatisfiedWildcard(bool caseSensitive, object condition, string str, ExecutionContext context) { WildcardPattern pattern = condition as WildcardPattern; if (pattern != null) { if (((pattern.Options & WildcardOptions.IgnoreCase) == WildcardOptions.None) != caseSensitive) { WildcardOptions options = caseSensitive ? WildcardOptions.None : WildcardOptions.IgnoreCase; pattern = new WildcardPattern(pattern.Pattern, options); } } else { WildcardOptions options2 = caseSensitive ? WildcardOptions.None : WildcardOptions.IgnoreCase; pattern = new WildcardPattern(PSObject.ToStringParser(context, condition), options2); } return pattern.IsMatch(str); }
protected override void ProcessRecord() { if (this.PSProvider == null || this.PSProvider != null && (int)this.PSProvider.Length == 0) { base.WriteObject(base.SessionState.Provider.GetAll(), true); return; } else { string[] pSProvider = this.PSProvider; for (int i = 0; i < (int)pSProvider.Length; i++) { string str = pSProvider[i]; PSSnapinQualifiedName instance = PSSnapinQualifiedName.GetInstance(str); if (instance == null || !WildcardPattern.ContainsWildcardCharacters(instance.ShortName)) { try { Collection<ProviderInfo> providerInfos = base.SessionState.Provider.Get(str); base.WriteObject(providerInfos, true); } catch (ProviderNotFoundException providerNotFoundException1) { ProviderNotFoundException providerNotFoundException = providerNotFoundException1; base.WriteError(new ErrorRecord(providerNotFoundException.ErrorRecord, providerNotFoundException)); } } else { WildcardPattern wildcardPattern = new WildcardPattern(instance.ShortName, WildcardOptions.IgnoreCase); foreach (ProviderInfo all in base.SessionState.Provider.GetAll()) { if (!all.IsMatch(wildcardPattern, instance)) { continue; } base.WriteObject(all); } } } return; } }
private void WriteTreeList(IList<ITree<IFileableCmisObject>> treeList, WildcardPattern wildcard) { if (treeList == null) { return; } foreach (var tree in treeList) { if (wildcard.IsMatch(tree.Item.Name)) { WriteObject(tree.Item); } if (tree.Children != null) { WriteTreeList(tree.Children, wildcard); } } }
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); } } } }
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); }
/// <summary> /// Returns true if help content in help info matches the /// pattern contained in <paramref name="pattern"/>. /// The underlying code will usually run pattern.IsMatch() on /// content it wants to search. /// </summary> /// <param name="pattern"></param> /// <returns></returns> internal virtual bool MatchPatternInContent(WildcardPattern pattern) { // this is base class implementation..derived classes can choose // what is best to them. return(false); }
/// <summary> /// Creates a new instance of a <see cref="CommandBreakpoint"/> /// </summary> public CommandBreakpoint(string script, WildcardPattern command, string commandString, int id) : this(script, command, commandString, null, id) { }
/// <summary> /// Called from <see cref="Parse"/> method to indicate /// the beginning of the wildcard pattern. /// Default implementation simply returns. /// </summary> /// <param name="pattern"> /// <see cref="WildcardPattern"/> object that includes both /// the text of the pattern (<see cref="WildcardPattern.Pattern"/>) /// and the pattern options (<see cref="WildcardPattern.Options"/>) /// </param> protected virtual void BeginWildcardPattern(WildcardPattern pattern) { }
internal virtual bool MatchPatternInContent(WildcardPattern pattern) { return(false); }
/// <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 (snapinQualifiedNameForPattern == null) { 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; } } } } }
/// <summary> /// Parses <paramref name="pattern"/>, calling appropriate overloads /// in <paramref name="parser"/> /// </summary> /// <param name="pattern">Pattern to parse.</param> /// <param name="parser">Parser to call back.</param> public static void Parse(WildcardPattern pattern, WildcardPatternParser parser) { parser.BeginWildcardPattern(pattern); bool previousCharacterIsAnEscape = false; bool previousCharacterStartedBracketExpression = false; bool insideCharacterRange = false; StringBuilder characterRangeContents = null; StringBuilder characterRangeOperators = null; foreach (char c in pattern.Pattern) { if (insideCharacterRange) { if (c == ']' && !previousCharacterStartedBracketExpression && !previousCharacterIsAnEscape) { // An unescaped closing square bracket closes the character set. In other // words, there are no nested square bracket expressions // This is different than the POSIX spec // (at https://www.opengroup.org/onlinepubs/9699919799/functions/fnmatch.html), // but we are keeping this behavior for back-compatibility. insideCharacterRange = false; parser.AppendBracketExpression(characterRangeContents.ToString(), characterRangeOperators.ToString(), pattern.Pattern); characterRangeContents = null; characterRangeOperators = null; } else if (c != '`' || previousCharacterIsAnEscape) { characterRangeContents.Append(c); characterRangeOperators.Append((c == '-') && !previousCharacterIsAnEscape ? '-' : ' '); } previousCharacterStartedBracketExpression = false; } else { if (c == '*' && !previousCharacterIsAnEscape) { parser.AppendAsterix(); } else if (c == '?' && !previousCharacterIsAnEscape) { parser.AppendQuestionMark(); } else if (c == '[' && !previousCharacterIsAnEscape) { insideCharacterRange = true; characterRangeContents = new StringBuilder(); characterRangeOperators = new StringBuilder(); previousCharacterStartedBracketExpression = true; } else if (c != '`' || previousCharacterIsAnEscape) { parser.AppendLiteralCharacter(c); } } previousCharacterIsAnEscape = (c == '`') && (!previousCharacterIsAnEscape); } if (insideCharacterRange) { throw NewWildcardPatternException(pattern.Pattern); } if (previousCharacterIsAnEscape) { if (!pattern.Pattern.Equals("`", StringComparison.Ordinal)) // Win7 backcompatibility requires treating '`' pattern as '' pattern { parser.AppendLiteralCharacter(pattern.Pattern[pattern.Pattern.Length - 1]); } } parser.EndWildcardPattern(); }
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) { int iteratorVariable0 = 0; string pattern = helpRequest.Target; string name = pattern; WildcardPattern iteratorVariable3 = null; bool iteratorVariable4 = !WildcardPattern.ContainsWildcardCharacters(pattern); if (!searchOnlyContent) { if (iteratorVariable4) { name = name + "*"; } } else { string target = helpRequest.Target; if (iteratorVariable4) { target = "*" + helpRequest.Target + "*"; } iteratorVariable3 = new WildcardPattern(target, WildcardOptions.IgnoreCase | WildcardOptions.Compiled); name = "*"; } PSSnapinQualifiedName instance = PSSnapinQualifiedName.GetInstance(name); if (instance != null) { foreach (ProviderInfo iteratorVariable6 in this._sessionState.Provider.GetAll()) { if (!iteratorVariable6.IsMatch(name)) { continue; } try { this.LoadHelpFile(iteratorVariable6); } catch (IOException exception) { if (!iteratorVariable4) { this.ReportHelpFileError(exception, iteratorVariable6.Name, iteratorVariable6.HelpFile); } } catch (SecurityException exception2) { if (!iteratorVariable4) { this.ReportHelpFileError(exception2, iteratorVariable6.Name, iteratorVariable6.HelpFile); } } catch (XmlException exception3) { if (!iteratorVariable4) { this.ReportHelpFileError(exception3, iteratorVariable6.Name, iteratorVariable6.HelpFile); } } HelpInfo cache = this.GetCache(iteratorVariable6.PSSnapInName + @"\" + iteratorVariable6.Name); if ((cache != null) && (!searchOnlyContent || cache.MatchPatternInContent(iteratorVariable3))) { iteratorVariable0++; yield return(cache); if ((iteratorVariable0 >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0)) { break; } } } } }
/// <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 } //if } // foreach if (matchFound) { _matchingResource = _matchingResourceList.GetEnumerator(); } else { return(null); } }//if if (!_matchingResource.MoveNext()) { _matchingResource = null; } else { return(_matchingResource.Current); } return(null); }
// Visit one the other variations: // - Dotting scripts // - Setting aliases // - Importing modules // - Exporting module members public override AstVisitAction VisitCommand(CommandAst commandAst) { string commandName = commandAst.GetCommandName() ?? GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string; if (commandName == null) { return(AstVisitAction.SkipChildren); } // They are trying to dot a script if (commandAst.InvocationOperator == TokenKind.Dot) { // . Foo-Bar4.ps1 // . $psScriptRoot\Foo-Bar.ps1 -Bing Baz // . ""$psScriptRoot\Support Files\Foo-Bar2.ps1"" -Bing Baz // . '$psScriptRoot\Support Files\Foo-Bar3.ps1' -Bing Baz DiscoveredModules.Add( new RequiredModuleInfo { Name = commandName, CommandsToPostFilter = new List <string>() }); ModuleIntrinsics.Tracer.WriteLine("Module dots {0}", commandName); } // They are setting an alias. if (string.Equals(commandName, "New-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "Microsoft.PowerShell.Utility\\New-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "Set-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "Microsoft.PowerShell.Utility\\Set-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "nal", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "sal", StringComparison.OrdinalIgnoreCase)) { // Set-Alias Foo-Bar5 Foo-Bar // Set-Alias -Name Foo-Bar6 -Value Foo-Bar // sal Foo-Bar7 Foo-Bar // sal -Value Foo-Bar -Name Foo-Bar8 var boundParameters = DoPsuedoParameterBinding(commandAst, commandName); var name = boundParameters["Name"] as string; if (!string.IsNullOrEmpty(name)) { var value = boundParameters["Value"] as string; if (!string.IsNullOrEmpty(value)) { // These aren't stored in DiscoveredExports, as they are only // exported after the user calls Export-ModuleMember. DiscoveredAliases[name] = value; ModuleIntrinsics.Tracer.WriteLine("Module defines alias: {0} = {1}", name, value); } } return(AstVisitAction.SkipChildren); } // They are importing a module if (string.Equals(commandName, "Import-Module", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "ipmo", StringComparison.OrdinalIgnoreCase)) { // Import-Module Module1 // Import-Module Module2 -Function Foo-Module2*, Foo-Module2Second* -Cmdlet Foo-Module2Cmdlet,Foo-Module2Cmdlet* // Import-Module Module3 -Function Foo-Module3Command1, Foo-Module3Command2 // Import-Module Module4, // Module5 // Import-Module -Name Module6, // Module7 -Global var boundParameters = DoPsuedoParameterBinding(commandAst, commandName); List <string> commandsToPostFilter = new List <string>(); Action <string> onEachCommand = importedCommandName => commandsToPostFilter.Add(importedCommandName); // Process any exports from the module that we determine from // the -Function, -Cmdlet, or -Alias parameters ProcessCmdletArguments(boundParameters["Function"], onEachCommand); ProcessCmdletArguments(boundParameters["Cmdlet"], onEachCommand); ProcessCmdletArguments(boundParameters["Alias"], onEachCommand); // Now, go through all of the discovered modules on Import-Module // and register them for deeper investigation. Action <string> onEachModule = moduleName => { ModuleIntrinsics.Tracer.WriteLine("Discovered module import: {0}", moduleName); DiscoveredModules.Add( new RequiredModuleInfo { Name = moduleName, CommandsToPostFilter = commandsToPostFilter }); }; ProcessCmdletArguments(boundParameters["Name"], onEachModule); return(AstVisitAction.SkipChildren); } // They are exporting a module member if (string.Equals(commandName, "Export-ModuleMember", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "Microsoft.PowerShell.Core\\Export-ModuleMember", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "$script:ExportModuleMember", StringComparison.OrdinalIgnoreCase)) { // Export-ModuleMember * // Export-ModuleMember Exported-UnNamedModuleMember // Export-ModuleMember -Function Exported-FunctionModuleMember1, Exported-FunctionModuleMember2 -Cmdlet Exported-CmdletModuleMember ` // -Alias Exported-AliasModuleMember // & $script:ExportModuleMember -Function (...) var boundParameters = DoPsuedoParameterBinding(commandAst, commandName); Action <string> onEachFunction = exportedCommandName => { DiscoveredCommandFilters.Add(exportedCommandName); ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: {0}", exportedCommandName); // If the export doesn't contain wildcards, then add it to the // discovered commands as well. It is likely that they created // the command dynamically if ((!WildcardPattern.ContainsWildcardCharacters(exportedCommandName)) && (!DiscoveredExports.Contains(exportedCommandName))) { DiscoveredExports.Add(exportedCommandName); } }; ProcessCmdletArguments(boundParameters["Function"], onEachFunction); ProcessCmdletArguments(boundParameters["Cmdlet"], onEachFunction); Action <string> onEachAlias = exportedAlias => { DiscoveredCommandFilters.Add(exportedAlias); // If the export doesn't contain wildcards, then add it to the // discovered commands as well. It is likely that they created // the command dynamically if (!WildcardPattern.ContainsWildcardCharacters(exportedAlias)) { DiscoveredAliases[exportedAlias] = null; } }; ProcessCmdletArguments(boundParameters["Alias"], onEachAlias); return(AstVisitAction.SkipChildren); } // They are exporting a module member using our advanced 'public' function // that we've presented in many demos if ((string.Equals(commandName, "public", StringComparison.OrdinalIgnoreCase)) && (commandAst.CommandElements.Count > 2)) { // public function Publicly-ExportedFunction // public alias Publicly-ExportedAlias string publicCommandName = commandAst.CommandElements[2].ToString().Trim(); DiscoveredExports.Add(publicCommandName); DiscoveredCommandFilters.Add(publicCommandName); } return(AstVisitAction.SkipChildren); }
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 is 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 CommandBreakpoint(string script, WildcardPattern command, string commandString, ScriptBlock action, int id) : base(script, action, id) { CommandPattern = command; Command = commandString; }
internal static IEnumerable <string> GetModulePath(bool preferSystemModulePath, ExecutionContext context) { List <string> list = new List <string>(); string environmentVariable = Environment.GetEnvironmentVariable("PSMODULEPATH"); if (environmentVariable == null) { SetModulePath(); environmentVariable = Environment.GetEnvironmentVariable("PSMODULEPATH"); } if (preferSystemModulePath) { list.Add(GetSystemwideModulePath()); } if (environmentVariable.Trim().Length != 0) { foreach (string str2 in environmentVariable.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { string pattern = str2.Trim(); try { ProviderInfo provider = null; if (context.EngineSessionState.IsProviderLoaded(context.ProviderNames.FileSystem)) { IEnumerable <string> resolvedProviderPathFromPSPath = context.SessionState.Path.GetResolvedProviderPathFromPSPath(WildcardPattern.Escape(pattern), out provider); if (provider.NameEquals(context.ProviderNames.FileSystem)) { foreach (string str4 in resolvedProviderPathFromPSPath) { list.Add(str4); } } } else { list.Add(pattern); } } catch (ItemNotFoundException) { } catch (System.Management.Automation.DriveNotFoundException) { } } } return(list); }
public override AstVisitAction VisitCommand(CommandAst commandAst) { string commandName = commandAst.GetCommandName(); if (string.IsNullOrEmpty(commandName)) { commandName = commandAst.CommandElements[0].ToString().Trim(new char[] { '"', '\'' }); } if (commandAst.InvocationOperator == TokenKind.Dot) { commandName = Regex.Replace(commandName, @"\$[^\\]*\\", "", RegexOptions.IgnoreCase); RequiredModuleInfo item = new RequiredModuleInfo { Name = commandName, CommandsToPostFilter = new List <string>() }; this.DiscoveredModules.Add(item); ModuleIntrinsics.Tracer.WriteLine("Module dots " + commandName, new object[0]); } if (((string.Equals(commandName, "New-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, @"Microsoft.PowerShell.Utility\New-Alias", StringComparison.OrdinalIgnoreCase)) || (string.Equals(commandName, "Set-Alias", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, @"Microsoft.PowerShell.Utility\Set-Alias", StringComparison.OrdinalIgnoreCase))) || (string.Equals(commandName, "nal", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "sal", StringComparison.OrdinalIgnoreCase))) { string str2 = this.GetParameterByNameOrPosition("Name", 0, commandAst); string str3 = this.GetParameterByNameOrPosition("Value", 1, commandAst); if (!string.IsNullOrEmpty(str2)) { this.DiscoveredAliases[str2] = str3; ModuleIntrinsics.Tracer.WriteLine("Module defines alias: " + str2 + "=" + str3, new object[0]); } } if (string.Equals(commandName, "Import-Module", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, "ipmo", StringComparison.OrdinalIgnoreCase)) { List <string> list = new List <string>(); string str4 = this.GetParameterByNameOrPosition("Function", -1, commandAst); if (!string.IsNullOrEmpty(str4)) { list.AddRange(this.ProcessExportedCommandList(str4)); } string str5 = this.GetParameterByNameOrPosition("Cmdlet", -1, commandAst); if (!string.IsNullOrEmpty(str5)) { list.AddRange(this.ProcessExportedCommandList(str5)); } string str6 = this.GetParameterByNameOrPosition("Alias", -1, commandAst); if (!string.IsNullOrEmpty(str6)) { list.AddRange(this.ProcessExportedCommandList(str6)); } string str7 = this.GetParameterByNameOrPosition("Name", 0, commandAst); if (!string.IsNullOrEmpty(str7)) { foreach (string str8 in str7.Split(new char[] { ',' })) { ModuleIntrinsics.Tracer.WriteLine("Discovered module import: " + str8, new object[0]); RequiredModuleInfo info2 = new RequiredModuleInfo { Name = str8.Trim(), CommandsToPostFilter = list }; this.DiscoveredModules.Add(info2); } } } if ((string.Equals(commandName, "Export-ModuleMember", StringComparison.OrdinalIgnoreCase) || string.Equals(commandName, @"Microsoft.PowerShell.Core\Export-ModuleMember", StringComparison.OrdinalIgnoreCase)) || string.Equals(commandName, "$script:ExportModuleMember", StringComparison.OrdinalIgnoreCase)) { List <string> list2 = new List <string>(); string arguments = this.GetParameterByNameOrPosition("Function", 0, commandAst); list2.AddRange(this.ExtractArgumentList(arguments)); string str10 = this.GetParameterByNameOrPosition("Cmdlet", -1, commandAst); list2.AddRange(this.ExtractArgumentList(str10)); foreach (string str11 in list2) { this.DiscoveredCommandFilters.Add(str11); ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: " + str11, new object[0]); if (!WildcardPattern.ContainsWildcardCharacters(str11) && !this.DiscoveredExports.Contains(str11)) { this.DiscoveredExports.Add(str11); } } list2 = new List <string>(); string str12 = this.GetParameterByNameOrPosition("Alias", -1, commandAst); list2.AddRange(this.ExtractArgumentList(str12)); foreach (string str13 in list2) { this.DiscoveredCommandFilters.Add(str13); if (!WildcardPattern.ContainsWildcardCharacters(str13) && !this.DiscoveredAliases.ContainsKey(str13)) { this.DiscoveredAliases.Add(str13, null); } } } if (string.Equals(commandName, "public", StringComparison.OrdinalIgnoreCase) && (commandAst.CommandElements.Count > 2)) { string str14 = commandAst.CommandElements[2].ToString().Trim(); this.DiscoveredExports.Add(str14); this.DiscoveredCommandFilters.Add(str14); } return(AstVisitAction.Continue); }
/// <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); } } } }
/// <summary> /// On Windows, just append <paramref name="arg"/>. /// On Unix, do globbing as appropriate, otherwise just append <paramref name="arg"/>. /// </summary> /// <param name="arg">The argument that possibly needs expansion.</param> /// <param name="usedQuotes">True if the argument was a quoted string (single or double).</param> private void PossiblyGlobArg(string arg, bool usedQuotes) { var argExpanded = false; #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against // the file system just like bash, etc. if (!usedQuotes && WildcardPattern.ContainsWildcardCharacters(arg)) { // See if the current working directory is a filesystem provider location // We won't do the expansion if it isn't since native commands can only access the file system. var cwdinfo = Context.EngineSessionState.CurrentLocation; // If it's a filesystem location then expand the wildcards if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { // On UNIX, paths starting with ~ or absolute paths are not normalized bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/'); // See if there are any matching paths otherwise just add the pattern as the argument Collection <PSObject> paths = null; try { paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false); } catch { // Fallthrough will append the pattern unchanged. } // Expand paths, but only from the file system. if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo)) { var sep = string.Empty; foreach (var path in paths) { _arguments.Append(sep); sep = " "; var expandedPath = (path.BaseObject as FileSystemInfo).FullName; if (normalizePath) { expandedPath = Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath); } // If the path contains spaces, then add quotes around it. if (NeedQuotes(expandedPath)) { _arguments.Append("\""); _arguments.Append(expandedPath); _arguments.Append("\""); } else { _arguments.Append(expandedPath); } argExpanded = true; } } } } else if (!usedQuotes) { // Even if there are no wildcards, we still need to possibly // expand ~ into the filesystem provider home directory path ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); string home = fileSystemProvider.Home; if (string.Equals(arg, "~")) { _arguments.Append(home); argExpanded = true; } else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) { var replacementString = home + arg.Substring(1); _arguments.Append(replacementString); argExpanded = true; } } #endif // UNIX if (!argExpanded) { _arguments.Append(arg); } }
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; } } } }
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; }