powershellcopy-item

Copy-item duplicating some directories in sub directories. (Real head-scratcher)


When copying a Windows profile, I am successfully copying and excluding the voluminous "AppData" folder. But the side effect is that in the backup folder, sub-folder "Documents" duplicates are showing up.

$UserProfPath = "C:\Users\" + $UserID
$UserProfPathAllItems = $UserProfPath + "\*"
$UserBkpPath = $BackupLocation + "\" + $UserID

Copy-Item -Path (Get-Item -Path $UserProfPathAllItems -Exclude ('Appdata')).FullName -Destination            $UserBkpPath -Force -Recurse 

This works, but it makes redundant "My Music", "My Pictures", and "My Videos" folders in the "Documents" sub-folder (but does not copy files); and that is the only redundant 3 folders it makes! Where in this logic would this line make these 3 redundant folders?


Solution

  • Those are hidden, system-defined junctions (junctions are akin to symbolic links to other directories) that exist solely for backward compatibility with pre-Vista versions of Windows.
    E.g., the legacy path $HOME\Documents\My Music simply redirects to $HOME\Music

    Your Copy-Item call includes -Force, which includes hidden items, so these system junctions are included in the copy operation and become regular, non-hidden, empty directories - this behavior is problematic, for the reasons discussed in the next section.

    Solution options:


    Background information:

    You can discover these system junctions in a given directory tree as follows:

    Get-ChildItem -Attributes Hidden+System+ReparsePoint -Recurse -ErrorAction Ignore $UserProfPath
    

    The fact that when such system junctions are copied they turn into regular directories in principle is somewhat justifiable: