Need Help With Script To Copy Files matching Filenames listed in text file

Hi,
I am new to PS and I am looking for a solution/script to perform below task.

Requirement: I have a text file contains list of filenames(ex: AB-12-LOG, XY-23H-LOG etc) and I need to copy all those listed files from the folder C:\2021\04April to C:\Destination

Any help with script would be very helpful.

Hi @rameshsagar, there wont be a script readily available here for this. But we can help you write one for sure.

  • First thing required here is to have a cmdlet to read the file, which will be Get-ChildItem

  • Then you would iterate through each lines in the file where each line is a filename, for that you will use ForEach-Object cmdlet.

  • Then its a matter of using Copy-Item cmdlet to copy using -Path and -Destination parameters. You would be using $_ as the current item during the iteration using ForEach-Object cmdlet (which is detailed in the cmdlet help and examples).

Hope above info helps you, let us know if you face any doubts in writing a script using above tips with your code.

1 Like

Thanks for the reply @kvprasoon

It would be helpful if you could help me with the code ‘to read filenames (one-by-one) listed in text and search for those files in the folder’

If you start to write some piece of code, then it wont be difficult to take it from there to discuss. That’s how forums helps us.

Sure. Thanks for the help.

@rameshsagar,

Please be sure to include and use the FullName property in the program code as this is the unique identifier for the file item. This reduces the chance of unintended outcomes when recursion or depth is specified.

-dicey

1 Like

It is defenetly not the best way to do it, but yeah. It works.
Note: I only had a 5 days crash course - dont judge me :smiley:

$sourcefolder = "C:\test\old"
$destinationfolder = "C:\test\new"
$inputfile = Get-Content C:\test\files.txt

$filelist = $inputfile.Split(",") 

foreach ($file in $filelist)
{
    Copy-Item $sourcefolder\$file.* -Destination $destinationfolder
}

You can go with " $file.* " if you dont want to write the file type into your txt. Otherwise just erase " .* "