function grep($searchPattern, $fileMatch = '*.*', [bool] $ignoreCase = $true){ if ($ignoreCase){ Get-ChildItem -Recurse -Filter $fileMatch | Select-String -Pattern $searchPattern | Format-Table -GroupBy Path -AutoSize } else { Get-ChildItem -Recurse -Filter $fileMatch | Select-String -Pattern $searchPattern -CaseSensitive | Format-Table -GroupBy Path -AutoSize } } grep AsFullName *.cs $true
The cmdlet above is called grep, but this does not apply to the verb-noun standard of Powershell. A better name could be Search-Files or something similar. The function uses the Get-ChildItem cmdlet with the recurse option to search all files (and folders) recursively from the current working directory and all its subfolders. This is then piped to Select-String and the flag -CaseSensitive is set if $ignorecase is set to $false. As you can see, the default value of the second and third parameter to the function /cmdlet is '*.*' for $fileMatch and $true for $ignoreCase. A function call is done in the code shown above as an example. Make note that only the first parameter is required, the search string. If a case sensitive search is desired, one must specify all three parameters. If it is desired to search through all files, use '*.*'. In my example, I am looking through some source code, and I am only interested in looking at the files with the extension '.cs' (C# source code files).
It is possible to compact the function or cmdlet above by making use of emulating the ternary operator, but the script above is easy should be easy to debug. If $ignoreCase is set to $false, the -CaseSensitive flag is used in the Search-String cmdlet in the script above.
The output of the command is shown below, when the working directory is set to the source code folder where I have cloned the source code of ShellStudio:
PS C:\toaurs-he\StudioShell\studioshell[ default ]> grep AsFullName *.cs Path: C:\toaurs-he\StudioShell\studioshell\src\CodeOwls.StudioShell\CodeOwls.StudioShell.Paths\Items\CodeModel\ShellCodeTypeReference.cs IgnoreCase LineNumber Line Filename Path ---------- ---------- ---- -------- ---- True 54 public string AsFullName ShellCodeTypeReference.cs C:\toaurs-he\StudioShell\studioshell\src\CodeOwls.StudioShell\CodeOwls.StudioSh... True 56 get { return _typeRef.AsFullName; } ShellCodeTypeReference.cs C:\toaurs-he\StudioShell\studioshell\src\CodeOwls.StudioShell\CodeOwls.StudioSh...
ShellStudio source code can be cloned at the following url:
ReplyDeletehttps://hg.codeplex.com/studioshell
Obviously, you need to download hg (Mercurial) for this, see the following url:
http://mercurial.selenic.com/