Copy the file, including its relative path

I need to copy a large number of files to the backup folder, but I want to save their relative paths. I need only certain 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 this:

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

The source paths have several 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\ } 

It just flushes all the files in C: \ backup \ and no path appears. Not sure how this part will be done.

+6
powershell
source share
4 answers

Something like this might 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 smart, but it is fast and dirty and works without much effort.

+6
source share

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

 resolve-path -relative 

So, to copy the filtered set of files from the current directory recursively to the 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 required to create parent directories

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

Of course, robocopy does all this, but there will be times when you want to do more specialized filtering or file management ...

+3
source share

Use robocopy.

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

Unfortunately. I did not notice that you want to add the .bak extension. I still think that using robocopy to copy files is recommended:

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

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 } 

a new element exists to force the creation of a path.

Jean Paul

+1
source share

All Articles