user209554
user209554

Reputation: 21

Copy-Item using Get-ChildItem in PowerShell

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?

Upvotes: 2

Views: 5974

Answers (2)

DanielV
DanielV

Reputation: 2700

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

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

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.

Upvotes: 5

Related Questions