powershellxcopymax-path

Recursively copy folders with long file names (more than 260 chars)


I am trying to automate copy/replication of drives. Many of the drives have long file names, that fail the process midway.

I was using this copy command, but both these fail.

XCOPY /E c:\folder-you-want-to-copy\*.* C:\destinationfolder\ 

copy-item -Path K:\* -Destination E:\ -Recurse -Force

Copy-Item : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 260 characters.

I then tried SO help power shell from here and SO help here, but the enable option was missing in Win 10 policy for my machine

How can I recursively copy the files from one drive to another drive with the long file names/path?


Solution

  • As of Powershell 5.1 there is a Registry setting that can be used to handle Long Paths within a Powershell script.
    Run the following command to check if the value of LongPathsEnabled is set to 1.

    Get-ItemProperty -Path HKLM:\System\CurrentControlSet\Control\FileSystem LongPathsEnabled
    

    Using an Administrator Powershell, execute the following command.

    Set-ItemProperty 'HKLM:\System\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -value 1
    

    This will allow the Copy-Item (and other *-Item commands) to avoid the 256 char limit, without having to modify the script.

    I added the following code to my script to check if this value is set, in case we move to a new build machine.

    $LongPath = Get-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\FileSystem" LongPathsEnabled
    if ($LongPath.LongPathsEnabled -ne 1) {
        Write-Host "LongPathsEnabled is not set. Build paths are likely to exceed 256 characters and will fail."
        Exit 1
    }