简体   繁体   中英

How to copy files based on their name in Powershell?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM