I have seen a lot of confusion recently over the use of Select-String.
One mis-conception is that you need to use Get-Content to pipe the file contents into Select-String. Not so. Select-String will read the file for you.
If you just want to scan the files in a single folder to find a specific string then Select-String can do the work for you
Select-String -Path C:\Test\*.txt -Pattern “trial” –SimpleMatch
If you need to work through a folder structure add get-ChildItem to the pipeline
Get-ChildItem -Path C:\Test -Filter *.txt -Recurse |
Select-String -Pattern “trial” –SimpleMatch
One line of PowerShell gives you a very powerful way of filtering the files recursively and testing their contents for a given string
Reblogged this on Depresso Gioioso.
Select-String seems to be a great way to quickly ‘grep’ or search thru a file (or set of files) for key phases or words. If its not too much trouble I have a few other questions about handling objects found after they’ve been found from using the Select-String CmdLet:
[1of4] I’m recursively searching thru many files, and want to pull out specific data in ‘fixed column’ positions from the line(s) that match the phrase I’m seeking, i.e. position 10 thru 15 of the line or position 6 thru the end of the line (which might be unknown).
What is your preferred method for handling this situation?
[2of4] Since I’m recursively searching thru files to find matching phrases, how can I obtain other directory service information about the matching files file(s) – this is more of a methodology technique question because I realize there are multiple ways of achieving this?
[3of4] Sometimes, I need to make two passes at seeking content in this file, once for the first occurrence; and a second grep for obtaining the last occurrence of a phrase. After the second pass, I figure placing the values into an array is the best way, then need to combine first and last values onto one output line {somewhere else}.
[4of4] It’s probably just me, but I’ve never gotten the switch ‘-context 5 or -context 2, 7′ to work predictably – where 5 lines before and after or 2 before and 7 after will come out – have you?
The documentation reads fairly straight forward and I use to use the Vax SEARCH command for many dependable years with this feature, but am coming up with scratch for a working ‘-context’.
Many thanks for any thoughts on these areas of this important verb