2

I am trying to copy a large number of files from a Windows system to a Unix share using PowerShell. I seem to be able to get so far, but not the whole solution.

I seem to be able to copy the files across as long as I don't mind where they are stored as it loses all folder structure. I have tried various methods posted here and elsewhere online to no avail.

Code:

gci -path "e:\company folders\\*" | Where-Object {$_.LastAccessTime -le (Get-Date).addyears(-2)} | Copy-Item -destination "\\\networkfolder\archive\company folders\"

I have tried several variations of this script, including using -recurse after the -path and after the -destination

The most success came from

gci -path "e:\company folders\*" | Where-Object {$_.lastaccesstime -le (Get-Date).addyears(-2)} | Copy-Item -destination "\\\networkshare\archive\company folder\" -recurse -container

But this only copied five out of the 43 folders..

What am I doing wrong?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user209554
  • 21
  • 1
  • 2
  • 1
    If you start a process which takes long or transfers a lot of files or deletes a lot of files, i suggest you to use the -whatif operation. This shows you what would happen if you go for your command. example : Get-Childitem C:\SomeFile\*.txt -Recurse | Remove-Item -WhatIf ..... After you saw what the script would do, you know if your script is wrong or it stops simply because it's too much load for it. – RayofCommand Dec 16 '13 at 16:40
  • 1
    Pretty much a duplicate of http://stackoverflow.com/questions/11694961/whats-the-proper-way-to-copy-files-while-preserving-folder-structure-in-powersh/11695329#11695329 – SpellingD Dec 16 '13 at 20:50

2 Answers2

5

Use robocopy (Windows equivalent of rsync) if you want to replicate a folder structure:

$src = ':\company folders'
$dst = '\\networkfolder\archive\company folders'
$age = (Get-Date).AddYears(-2).ToString('yyyyMMdd')

& robocopy "$src" "$dst" /s /maxlad:$age

Replace /s with /e if you want to include empty subfolders as well.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 3
    Wow, why have I been so hooked on getting powershell copy-item to run this task? Used PS to set the variables and run robocopy and it just worked.... Thanks Ansgar! – user209554 Dec 16 '13 at 16:55
  • And i was wondering why you wanted to use powershell, we use robocopy as well for that purposes. :D – RayofCommand Dec 16 '13 at 16:58
0

The following script copies the files and keeps the folder structure (just in case), uses a specific filter.

$sourceDir = 'c:\temp'
$targetDir = 'c:\backup'

#Get the files based on a filter and copy them including folder structure
dir -Path $sourceDir -Filter *interop*.* -Recurse | foreach {
    $targetFile = $targetDir + $_.FullName.Substring($sourceDir.Length);
    New-Item -ItemType File -Path $targetFile -Force;
    Copy-Item $_.FullName -Destination $targetDir;
} -Verbose

Based on this original response

DanielV
  • 2,076
  • 2
  • 40
  • 61