Author Posts

March 28, 2018 at 3:04 pm

Hi,

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:

192.168.1.1:1234.png
192.168.1.2:5678.png
192.168.1.3:9123.png
192.168.1.4:4567.png

FileNames.txt contains:

192.168.1.4
192.168.1.2

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

March 28, 2018 at 3:14 pm

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:

"*Entry1
Entry2
...
LastEntry*"

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

March 28, 2018 at 4:13 pm

Thanks for the help Joel!

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

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

March 28, 2018 at 4:21 pm

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
}

March 29, 2018 at 1:26 am

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.

Beginner sites and tutorials

Help with teaching others Powershell
'reddit.com/r/PowerShell/comments/7oir35/help_with_teaching_others_powershell'