开发者

Copy a file including it's relative path

I need to copy a large number of files to a backup fol开发者_Python百科der but I want to maintain their relative paths. I only need specific files; i.e.

C:\scripts\folder\File.ext1
C:\scripts\folder2\file2.ext2
C:\scripts\file3.ext1

But I only need to copy the ext1 files like so:

C:\backup\folder\File.ext1.bak
C:\backup\file3.ext1.bak

The source paths are of multiple depths. This is what I have to copy the files:

$files = gci -path C:\scripts\ -recurse -include *.ext1 
$files | % { Copy-Item $_ "$($_).bak"; move-item $_ -destination C:\backup\ }

This just dumps all the files into C:\backup\ and does not appear to get any of the paths. Not sure how that part would be done.


Something like this could work:

gci -path C:\scripts\ -recurse -include *.ext1 | 
  % { Copy-Item $_.FullName "$($_.FullName).bak"
      move-item $_.FullName -destination ($_.FullName -replace 'C:\\scripts\\','C:\backup\') }

It is not clever, but it's quick & dirty and works without a lot of effort.


get-childitem returns absolute paths, but you can make them relative to the current working directory as follows:

resolve-path -relative

So to copy a filtered set of files from the current directory recursively to a destination directory:

$dest = "c:\dest"
$filter = "*.txt"

get-childitem -recurse -include $filter | `
    where-object { !$_.PSIsContainer } | `
    resolve-path -relative | `
    % { $destFile = join-path $dest $_; new-item -type f $destFile -force | out-null; copy-item $_ $destFile; get-item $destfile; }

new-item is needed to create the parent directories

get-item provides a display of all the new files it created

Of course robocopy does all this, but there will be times when you want to do more special filtering or filename mangling...


Use robocopy.

robocopy c:\scripts c:\backup *.ext1 /s

Oops. I failed to notice you wanted to add the .bak extension too. I still think it is a good idea to use robocopy to copy the files then:

dir c:\backup -recurse -include *.ext1 | % { ren $_ "$_.bak" }


You can try this

Clear-Host
$from = "'C:\scripts\"
$to = "'C:\backup\"
$inc = @('*.ext1', '*.extx')
$files = get-childItem  -path $from -include $inc -Recurse
$files | % {$dest = (Join-Path $to $($_.FullName+".bak").SubString($from.length)); $dum = New-Item -ItemType file $dest -Force; Copy-Item -Path $_ -Destination $dest  -Recurse -Force } 

the new-item is there in order to force path creation.

Jean Paul

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜