Home > database >  How to copy files based on their name in Powershell?
How to copy files based on their name in Powershell?

Time:12-10

I am trying select files form a large directory contains certain numbers. Right now I have this.. it is copy all files in the directory.. It should be a simple little script.. however it's driving me nuts..

$files=Get-Content nametofind.txt
ForEach($file in $files){
Copy-Item "source\*.xml" -Destination "selected"  | where{$_.name -contains $($file)} 
}

What am I missing?

Extract of text file:

27216
27658
27716
27793
27961
27975
28599
28665
28931
29076
29077
29079
29080
29582

This goes on for ca. 2500 lines

And the file name that I am searching in is of the format

L_20211103_110803_8540_77498.xml

The last segment of the filename before the extension is the segment of interest.

Thanks

CodePudding user response:

You can keep things simple by using wildcards in the Copy-Item command:

$files=Get-Content nametofind.txt
ForEach($file in $files){
  Copy-Item "source\*$file*.xml" -Destination "selected"
}

use the -whatif flag for the Copy-Item command to verify that what would occur is the desired behavior.

  • Related