6

I have to following directory structure:

fold1
 - file1
 - file2

fold2
 - file1

I am trying to test to see if the folders are identical, and if they arent, copy fold1 to fold2 and overwrite any different files. This is what I have tried:

$fold1 = Get-ChildItem -Recurse -path C:\fold1
$fold2 = Get-ChildItem -Recurse -path C:\fold2
$isDif = Compare-Object $fold1 $fold2
if ($isDif -eq $null) {
    Write-Host "Folders Are Identical"
}
else {
    Write-Host "Folders Are Different"
    Copy-Item -Path $fold1.FullName -Destination $fold2.FullName -Recurse -Force
}

But when I run it, it says the folders are different, but it doesn't copy anything over. No errors or anything, it just doesn't work.

3 Answers 3

6

I ended up using robocopy instead:

robocopy c:\fold1 c:\fold2 /s
Sign up to request clarification or add additional context in comments.

3 Comments

I've spent so long trying to get copy-item to work that I'm starting to think this or xcopy really is the best answer...
I found it hard to believe but yes - Copy-Item is actually unreliable...
Seriously... I tried about 30 minutes to make Copy-Item work, but couldn't make it. Perhaps it's an issue with permission? But rocobopy worked staright away...
2

i, just do it

 $path1 = "C:\temp2\*"
 $path2 = "C:\temp3"

 Copy-Item -Path $path1 -Destination $path2 -Recurse -Force -ErrorAction Continue

4 Comments

This is much more efficient than my answer. I just did not know if Alan wanted the check the folder contents before the copy.
It is unnecessary to check. If the files exist, they will not be overwritten. :)
I agree if you are going to override the files regardless.
"Compare-Object $fold1 $fold2" compare only path difference, not content files difference ;) My code did the same thing
1

This is how I would recommend doing the task in powerhsell. It makes it much easier if you create path variables, that way you are not trying to insert records into a directory object.

$path1 = "C:\fold1"
$path2 = "C:\fold2"
$fold1 = Get-ChildItem -Recurse -path $path1
$fold2 = Get-ChildItem -Recurse -path $path2
$isDif = Compare-Object $fold1 $fold2
if ($isDif -eq $null) {
    Write-Host "Folders Are Identical"
}
else 
{
    Write-Host "Folders Are Different"
    ForEach($file in $fold1)
    {
        if($fold2 -notcontains $file)
        {
            Copy-Item -Path $file.FullName -Destination $path2 -Recurse -Force
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.