Moving Files Based on Strings from Input Text File


I am quite new to PowerShell, and I am struggling with what should be a simple script.

I wish to move files within a source folder to a destination folder, if part of their filename matches strings within a text file.

An example:

Source = .\SourceFiles
Destination = .\DestinationFiles
FileNamesToMatch = .\FileNames.txt

Source contains the following:

FileNames.txt contains:

I wish to move the files from Source to Destination based on a wildcard match from each string in FileNames.txt.

The following is code similar to what I want to achieve, however it is meant for a single string rather than the contents of a text file so it fails when passing it the variable $FileNamesToMatch:

$Source = .\SourceFiles
$Destination = .\DestinationFiles
$FileNamesToMatch = Get-Content .\FileNames.txt

Get-ChildItem -Path $Source -Filter "*$FileNamesToMatch*" | Move-Item -Destination $Destination

I hope this makes sense! Thanks

Your issue is that you’re passing the entire thing into the parameter and putting wildcards around it. You need wildcards on every entry. The string -Filter gets would end up something like this:


So you need to do this:

$FileNamesToMatch = Get-Content '.\FileNames.txt' | ForEach-Object {

Then -Filter will probably work, and if not, swap it for -Include. :slight_smile:

Thanks for the help Joel!

I had to edit it slightly as follows, but it now works :smiley:

$Source = '.\SourceFiles'
$Destination = '.\DestinationFiles'
$FileNamesToMatch = Get-Content '.\FileNames.txt' | ForEach-Object {
    Get-ChildItem -Path $Source -Filter "*$_*" | Move-Item -Destination $Destination

Nice Work!!

You can probably remove the $FileNamesToMatch variable, really, it won’t hold that much of use. It’ll end up just storing the references to the moved objects, so if you need those, awesome, but if not you can just have that bit be:

Get-Content '.\FileNames.txt' | ForEach-Object {
    Get-ChildItem -Path $Source -Filter "*$_*" | Move-Item -Destination $Destination

New to PoSH, means be sure to look to these resources to get a firm start / understanding of the whys and wherefors.
Well, that and to save yourself a good deal of unnecessary frustration.
Help with teaching others Powershell ''