I am scripting some file syncing and having a frustrating time. The biggest issue is trying to work around a few files that are flagged as “read-only.” In the examples, assume sourcefile.txt is “read-only.”
PS> copy-item sourcefile.txt c:\sourcefile.txt -force
If this is the first time copying, this will work just fine because the destination file is new.
PS> copy-item sourcefile.txt c:\sourcefile.txt -force
This will now give an error because c:\sourcefile.txt is read only.
PS> move-item sourcefile.txt c:\sourcefile.txt -force
This will always work.
While this isn’t so bad, I don’t want to move folders over without first going through them to make sure the new folder isn’t leaving out something from the old folders, if that makes sense.
So far, my solution is way more complex than I think it should be. I read through all folders and determine if the folder is new or already exists at the destination. If it is new, I move-item it over. I then copy all non-containers that are left. Then I remove all the leftover source containers. Please excuse the variable names and lack of tabs showing up.
$shortpathdest = "\\SERVER\FILES\Installed" $shortpathsource = "\\SERVER\FILES\ToInstall" $items = get-childitem $shortpathsource -recurse | where {$_.psIscontainer -eq $true} If ($items) { foreach ($i in $items) { $fullsourcepath = $i.FullName $fullsourcepath = $fullsourcepath.Replace($shortpathsource,"") $fullpathdest = $shortpathdest + $fullsourcepath If (test-path $fullpathdest){ } Else { move-item $($i.FullName) $longpathdest -force} } } $items2 = get-childitem $shortpathsource -recurse | where {$_.psIscontainer -eq $false}
If ($items2) { foreach ($i in $items2) { $fullsourcepath = $i.FullName $fullsourcepath = $fullsourcepath.Replace($shortpathsource,"") $fullpathdest = $shortpathdest + $fullsourcepath move-item $($i.FullName) $fullpathdest -force } } Remove-item $shortpathsource\* -recurse -force
I’m come across this similar problem and I find it incredibly frustrating. Did you ever find a solution that didn’t require the above script (as one issue with it is that it doesn’t maintain directory structures during a -recurse, which I need), perhaps using the native code with just a tweaking of parameters?