PowerShell move all files containg exact string in their body

41 Views Asked by At

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

2

There are 2 best solutions below

0
TP95 On BEST ANSWER

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"
0
Hassan shah On

You can change your PowerShell script to utilize the -SimpleMatch parameter with Select-String in order to guarantee that only files with the precise string match in their body (text file contents) are moved to the subfolder. By using a literal match rather than a regular expression match, this argument makes sure that only files that contain the precise string are chosen. This is the revised script:

Code Copier for PowerShell

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

Get-ChildItem $source -Filter *.txt | ForEach-Object {
    if (Select-String -Path $_.FullName -Pattern "Sea" -SimpleMatch) {
        Move-Item $_.FullName -Destination $destination
    }
}

To find the precise string "Sea" in every text file's contents, use Select-String with the -SimpleMatch option. The file is transferred to the target directory indicated by $destination if a match is discovered. By making this change, matches with substrings are prevented and only files containing the precise string "Sea" in their body are moved to the subdirectory.