PowerShell : Find "string" in multiple files and move to subfolder

 If you have a requirement to search though a list is folders and find content within those files and move them to a subfolder then PowerShell can help you out here massively, especially if you have lots of files.

# Set the keyword and the path to the folder where you want to search
$keyword = "Bears"
$searchPath = "C:\BearTest" # Replace this with your desired folder path

# Create a subfolder to move the matching files
$destinationFolder = Join-Path -Path $searchPath -ChildPath "MatchedFiles"
if (-not (Test-Path -Path $destinationFolder)) {
    New-Item -Path $destinationFolder -ItemType Directory | Out-Null
}

# Search for files containing the keyword and move them to the subfolder
Get-ChildItem -Path $searchPath -Recurse | Where-Object { $_.PSIsContainer -eq $false -and (Get-Content $_.FullName | Select-String -Pattern $keyword -Quiet) } | ForEach-Object {
    $destinationPath = Join-Path -Path $destinationFolder -ChildPath $_.Name
    Move-Item -Path $_.FullName -Destination $destinationPath -Force
    Write-Host "Moved $($_.Name) to $destinationPath"
}


That should look like this:


This will search the "searchpath" and find the keyword "bears" then move the valid files to a folder called "MatchedFiles" as a subdirectory in the same folder you specify in searchpath.

When you run the script it will tell you what files are being moved based on the keyword search:






Previous Post Next Post

Ω†Ω…ΩˆΨ°Ψ¬ Ψ§Ω„Ψ§ΨͺΨ΅Ψ§Ω„