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.
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'.
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"