Filtering for strings in PowerShell

荒凉一梦 提交于 2020-01-07 02:25:09

问题


I would like to implement some custom cmdlets that filter some object by name, and I would like to use wild-card enabled search like for common cmdlets (Get-ChildItem and Get-Process).

How can I implement this kind of search? Are there some examples or even some reusable components? Any examples?


回答1:


For the most part, these types of cmdlets leverage the WildcardPattern class.

Here's an example of how to use it directly from the PowerShell prompt:

PS>$w = New-Object System.Management.Automation.WildcardPattern "*foo*"
PS>$w.IsMatch("foobar")
True
PS>$w.IsMatch("barbar")
False



回答2:


You can define your own filter by piping a collection of objects to Where-Object (or the short-form ?).

For example, if you get a collection of file objects by doing gci (alias of Get-ChildItem), you can display only the ones that have the text log in them by doing this: gci | ?{$_.name -match "log"}.



来源:https://stackoverflow.com/questions/10242482/filtering-for-strings-in-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!