Author Posts

May 25, 2017 at 7:54 pm

I want a script that looks for a particular string pattern or patterns in a given directory and started with the following:

Set-location C:\Users\thchen\Desktop\dprogs
Get-ChildItem -Recurse | Select-String -Pattern ':\' -SimpleMatch | 
group path | select name | Export-Csv -Path C:\Users\thchen\Desktop\TestMultiPattern.csv -Encoding ASCII -NoTypeInformation

The script above works beautifully without problem. When I open the csv file, cell A1 contains the word 'Name' and the rest of column A contains all the files under C:\Users\thchen\Desktop\dprogs containing the text pattern ':\'. However, I am looking for more than one string pattern. I want a list of all files that contains either ':\' or '\\'. So I modified my code to

Get-ChildItem -Recurse -File | 
where {($_.FullName | Select-String -Pattern (':\') -SimpleMatch) -or ($_.FullName | Select-String -Pattern ('\\') -SimpleMatch)}  | 
group path | select name | 
Export-Csv -Path C:\Users\thchen\Desktop\Output3.csv -Encoding ASCII -NoTypeInformation

Now when open the output csv file, all it contains is the word 'Name' in cell A1 and the rest of column A are empty. Can anybody see what I might have done wrong? Thanks for any help.

May 26, 2017 at 9:25 am

I had to adjust a little, but look at this:

Get-ChildItem -Recurse -File | where {$_.FullName -match ":\\try\\n" -or ":\\try\\d" } |select name

The group path is messing things up, but you can adjust it:

Get-ChildItem -Recurse -File | where {$_.FullName -match ":\\try\\n" -or ":\\try\\d" }|group path |select -ExpandProperty group|select name

May 26, 2017 at 1:31 pm

Thanks Chris. After some experiments, I realized if I want to find more than one pattern using Select-string, simply list out all patterns and separate them with comma like this:

Set-location C:\Users\thchen\Desktop\dprogs
Get-ChildItem -Recurse -File | Select-String -Pattern ':\', '\\' -SimpleMatch | 
group path | select name | Export-Csv -Path C:\Users\thchen\Desktop\TestMultiPattern.csv -Encoding ASCII -NoTypeInformation

The script above gives returns strings containing ':\' OR '\\' which is what I am looking for. So I am all good now. And according to example 7 from Microsoft Documentation, You can also use it to exclude certain patterns like this:

Select-String -Path "process.txt" -Pattern "idle, svchost" -NotMatch

But I am now wondering what if I am looking for both ':\' AND '\\' in a file?