akrabi
akrabi

Reputation: 4284

PowerShell Copy-Item PathTooLongException

I have a PowerShell script where I need to copy to a folder recursively, replacing all the files in it:

Copy-Item -Path $source -Destination $destination -Recurse -Force -Verbose

Since some of the files in the destination folder have a path that exceeds 260 chars I am getting a PathTooLongException.

I have read about these possible solutions:

  1. Use robocopy
    • I rather use pure PowerShell
  2. Enable long paths in registry & group policy
    • requires the user to have to restart his console and I also prefer not changing the user's registry.
  3. Use a \\?\ prefix for the paths

As I said, I rather not use the first two, the third solution (\\?\) should be fine for me, but the files are not actually being copied.

When it executes it completes immediately and no output from the command is generated. As a result, the files in the destination are not replaced with the files from the source.

Any ideas?

Upvotes: 5

Views: 5966

Answers (1)

henrycarteruk
henrycarteruk

Reputation: 13217

The \\?\ prefix makes use of the unicode version of Windows API, this needs to use the LiteralPath param instead of Path:

Copy-Item -LiteralPath '\\?\C:\folder\subfolder' -Destination 'D:\folder'

The syntax for UNC path \\server\share\folder is slightly different \\?\UNC\server\share\folder

(Not specifically relevant to you, but for future reference if anyone stumbles across this answer)

Upvotes: 4

Related Questions