Question

Using tips gleaned from this, this, and this, I've finally been able to get a series of file backup scripts going. However, there's one little thing that I've been unable to solve. No runtime errors, but when I run this script,

$originalPath = "\\Server\Path\_testData\"
$backupPath   = "\\Server\Path\_backup\"
#       
function supportBackup 
{
  "$($originalPath) copying DOC XLS PPT JPG GIF PDF WAV AVI to $($backupPath)"
  Get-ChildItem $originalPath\* -Include *.doc*, *.xls*, *.ppt*, *.jpg, *.gif, *.pdf, *.wav, *.avi | `
  foreach { 
    $targetFile = $backupPath + $_.FullName.SubString($originalPath.Length); 
    New-Item -ItemType File -Path $targetFile -Force;  
    Copy-Item $_.FullName -destination $targetFile 
  } 
  "Support File Backup Completed"
} 
supportBackup

The original file path gets dumped into the destination directory instead of just the files.

What I want:

\\Server\Path\_backup\files-from-testData-directory

What I get:

\\Server\Path\_backup\_testData\files-from-testData-directory

I know the problem is closely related (if not identical) to this question, but after studying it and trying to apply some of the wisdom from there, using various iterations of the $_.Name variables, I realize I don't have as good an understanding as I thought I did. I need someone to explain to me HOW the destination path and filename are being constructed with the given variables, and what alternate variables (or code) I need to use to achieve my desired results. There's something that's not clicking for me and I need help understanding it.

Was it helpful?

Solution

You're trying too hard. This should suffice:

$originalPath = '\\Server\Path\_testData'
$backupPath   = '\\Server\Path\_backup'
$extensions   = *.doc*,*.xls*,*.ppt*,*.jpg,*.gif,*.pdf,*.wav,*.avi

function supportBackup {
  "$($originalPath) copying DOC XLS PPT JPG GIF PDF WAV AVI to $($backupPath)"
  Get-ChildItem "$originalPath\*" -Include $extensions |
    Copy-Item -Destination "$backupPath\" -Force 
  "Support File Backup Completed"
} 

supportBackup

You can pipe the results of Get-ChildItem directly into Copy-File. The destination path must end with a backslash, though, otherwise the instruction would try to replace the folder $backupPath with a file of the same name, thus causing an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top