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 move all files containg exact string in their body

This is somewhat based on:

Powershell Move Files With Matching Substrings

In that question, the concern is to move files with substrings in the file title to the subdirectory.

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

In my case, I want to move files that match an exact string in their body (i.e. contents of text file) to the subdirectory.

Based on the above question’s answers, I have worked out:

$source = 'C:\ListOfWater\'
$destination = 'C:\ListOfWater\Seas'

Get-ChildItem $source -filter *.txt  | Select-String -List "Sea" | ForEach-Object {
Move-Item $PSItem.Path -Destination $destination
}

However, it will pick up words that match the substring, instead of ‘whole word matching’.

>Solution :

Use regex for exact matching strings like:

Get-ChildItem $source -filter *.txt  | Select-String -List "^Sea$" | ForEach-Object {
Move-Item $PSItem.Path -Destination $destination
}

The ^ and $ matches the start and end. You can be more explicit and use word boundaries with:

"\bSea\b"
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