PowerShell: how to copy only selected files from the source directory?

I am new to Powershell trying to run a simple script.

I have a list of files that I want to copy from some src_dir to dst_dir. I wrote a simple script (which is clearly wrong, since it did not do anything when I executed it).

Can someone please help check what I'm doing wrong?

# source and destionation directory $src_dir = "C:\Users\Pac\Desktop\C4new" $dst_dir = "C:\Users\Pac\Desktop\csci578-hw3\Prism\C4new" # list of files from source directory that I want to copy to destination folder # unconditionally $file_list = "C4newArchitecture.java", "CustomerData.java" # Copy each file unconditionally (regardless of whether or not the file is there for($i=0; $i -le $file_list.Length - 1; $i++) { Copy-Item -path $src_dir+$file_list[$i] -dest $dst_dir -force } 
+4
source share
3 answers

Oh, that was pretty easy:

 # source and destionation directory $src_dir = "C:\Users\Pac\Desktop\C4new\" $dst_dir = "C:\Users\Pac\Desktop\csci578-hw3\Prism\C4new" # list of files from source directory that I want to copy to destination folder # unconditionally $file_list = "C4newArchitecture.java", "CustomerData.java", "QuickLocalTransState.java", "QuickLocalTransState_AbstractImplementation.java", "SaveSessionOK.java", "SessionID.java", "UserInterface.java", "UserInterface_AbstractImplementation.java" # Copy each file unconditionally (regardless of whether or not the file is there foreach ($file in $file_list) { Copy-Item $src_dir$file $dst_dir } 

As a programmer, I love foreach!

+9
source

Assuming the files are directly unde $ src_dir, you can make this a little easier, i.e. copy can be single line:

 $file_list | Copy-Item -Path {Join-Path $src_dir $_} -Dest $dst_dir -ea 0 -Whatif 

-ea is an alias for the -ErrorAction parameter, and a value of 0 corresponds to SilentlyContinue. This causes the Copy-Item instance to ignore errors you might get if one of the source files did not exist. However, if you encounter problems, temporarily remove this option so that you can see error messages.

When entering this material interactively, I usually use shortcuts similar to this, but in scripts it is better to indicate its readability. Also note that the -Path parameter can accept a script block, i.e. script in braces. Technically, the Copy-Item cmdlet never sees a script block, but only the results of its execution. This works in the general case for any parameter that accepts an input channel. Remove -WhatIf so that the command actually executes.

+11
source
 Get-ChildItem -Path $srcDir | Where-Object { $fileNames -contains $_.Name } | Copy-Item -Destination $dstDir 

This is really convenient in some scenarios, for example:

 Get-ChildItem -Filter *.ocr.txt | Copy-Item -Destination $dstDir 
0
source

All Articles