tags:

views:

289

answers:

2

I'm a Powershell newbie, trying to get a simple script to run.

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

Could someone please help check to see 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
}
+1  A: 

Oh..that was actually 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 the foreach!

ShaChris23
+3  A: 

Assuming that the files are directly unde $src_dir you can do this a bit more simply ie the copy can be a one-liner:

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

-ea is the alias for the -ErrorAction parameter and 0 value corresponds to SilentlyContinue. This causes the Copy-Item to ignore errors like you would get if one of the source files didn't exist. However, if you are running into problems temporarily remove this parameter so you can see the error messages.

When typing this stuff interactively I tend to use shortcuts like this but in scripts it is better to spell it out for readability. Also notice that the -Path parameter can take a scriptblock i.e. script in curly braces. Technically the Copy-Item cmdlet doesn't ever see the scriptblock, just the results of its execution. This works in general for any parameter that takes pipeline input. Remove the -WhatIf to have the command actually execute.

Keith Hill
wow..that looks cool. thanks for sharing the info!
ShaChris23