How to Handle Long File Paths in PowerShell?

November 21, 2025 7 answers
Asked by 3pm dental visit
I'm trying to compare the contents of two directories to verify if a robocopy operation was successful, but I'm running into a problem with long file paths. Even after I've enabled long file paths in Group Policy Editor and the Registry, and added '\?' before my file paths in the variables, I'm still getting errors. Here's the script I'm working with: ``` $array1 = @(Get-ChildItem -LiteralPath 'C:SourcePath' -Recurse | Select-Object FullName) $array2 = @(Get-ChildItem -LiteralPath 'C:DestinationPath' -Recurse | Select-Object FullName) $result = @() $array2 | ForEach-Object { $item = $_ $count = ($array1 | Where-Object { $_ -eq $item }).Count $result += [PSCustomObject]@{ Item = $item Count = $count } } ``` I received this error with the script: "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 248 characters." I also encountered an error with the '\?' prefix stating that there are illegal characters in the path. Does anyone have any suggestions on how to get around this?

Answers

!conclude otherwise
I recommend using [this](https://ntfssecurity.readthedocs.io/en/latest/Cmdlets/Get-ChildItem2/). It's a command that might help alleviate some of the issues you're facing with file paths.
Reply to this answer
+Need a hand drill
Have you tried using the `subst` command? It can really make dealing with long file paths simpler. For example: `subst q: c:somereallylongfilepathmoregobbleygook` and then access it through the `q:` drive.
Reply to this answer
2.ways.home
Have you checked if you've set the [LongPathsEnabled](https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation?tabs=registry#enable-long-paths-in-windows-10-version-1607-and-later) registry value? After making changes there, a system restart might be necessary for it to take effect. This should allow you to work with extremely long paths in PowerShell, like this: `mkdir -Path ("${env:TEMP}" + 'foo' * 8000)`.
Reply to this answer
~peatcore9
You could try switching to PowerShell Core version 7.0 or later. It handles long file names and the `\?` prefix automatically, making it way easier to work with long paths compared to PowerShell 5.1.
Reply to this answer
!MarkTheEdge
The way you structure your paths matters too. For instance, with UNC paths, you can exceed 30,000 characters. Just make sure you're formatting your paths right. For example: `\?C:SourceFolder`.
Reply to this answer
sieve mesh size
I dealt with this recently and Long Path Tool helped get rid of the file.
Reply to this answer
OPEN CIRCUIT
Using LongPathTool makes handling path errors easier.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions