Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading