简体   繁体   中英

Is it possible to copy only few files from source directory using Copy-Item?

I am new to powershell and still learning. I copy files from local directory to remote server directory. It works fine but looking for an option to copy only few files say 5 from a shared path to remote(the source directory has thousands of file and I dont need them all for my test)

Copy-Item -Path "C:\source\Documents\" -Destination "C:\Program Files\target" -ToSession $session

How can I limit the number of files to be copied? Thanks

You have two options here. One is to use -Filter parameter in Copy-Item cmdlet if you can do your filtering with the FileSystem filter language . Use also parameter -Recurse if your files can be placed in subdirectories (those subdirectories are copied with their file trees intact). But you cannot use it if you want say first 5 matches.

Example:

Copy-Item -Path "C:\source\Documents\" -Destination "C:\Program Files\target" -ToSession $session -Recurse -Filter "File*.txt"

In the case you need select only first 5 files I would find (using Get-ChildItem cmdlet) them with your criteria first and copy it after that. You can do something like that (files will be copied to destination without directories)

  1. Using the FileSystem filter language. This code will find your files (only files) in path C:\source\Documents\ filter it by name with wildcard (File*.txt), select first 5 and copy it to destination on remote computer from $session variable

     dir "C:\source\Documents\" -Filter "File*.txt" -Recurse -File | select -First 5 | Copy-Item -Destination "C:\Program Files\target" -ToSession $session
  2. Using regex pattern for filtering your files. This code will find your files (only files) in path C:\source\Documents\ , filter it by regex pattern (use -match if you want to have it case sensitive) -> FileXXX.txt, where XXX are numbers 0-9, select first 5 files and copy it to destination on remote computer from $session variable

     dir "C:\source\Documents\" -Recurse -File |? {$_.Name -imatch "^File\d{3}.txt$"} | select -First 5 | Copy-Item -Destination "C:\Program Files\target" -ToSession $session

*If you want to copy hidden files, use -Force parameter.

Try Use this Copy-Item (gci "C:\source\Documents" | select -first 5).Fullname -Destination "C:\Program Files\target" -ToSession $session

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