Powershell – Search for Pattern and Copy

i have a bunch of *.CSV Files. Huge *.CSV Files. I try to search for a specific pattern in these Files called "Secure". If found, the script shall copy it to a folder.

It works, but it has one Problem i could’nt solve.
In some files, the Word i’m looking for is present more than once. Now my script searches for the word, finds it and copies it. Then it searches in the same file again, finds the pattern again and copies again.

But it should copy after the first find of the word and then search in the next *.CSV file and not in the same again.

i tried a bunch of things "-SimpleMatch" or "-First 1"

the Code so far is :

Select-String -Path 'C:\Tools\Test\*\*.csv' -Pattern "Secure" | Select -first 1 | Copy-Item -Destination C:\Tools\Found -Verbose

can someone help me ?

Thank you!

>Solution :

Use Get-ChildItem to discover the initial set of files, then use Select-String on one file at a time. This way Select -First 1 will return after the first match in each file, rather than breaking the whole pipeline after outputting the first file:

Get-ChildItem -Path 'C:\Tools\Test\*\*.csv' |Where-Object { $_ |Select-String -Pattern "Secure" |Select -First 1 } |Copy-Item -Destination C:\Tools\Found -Verbose

Leave a Reply