How to Handle Long File Paths in PowerShell?

0
60
Asked By TechSavvyNinja92 On

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?

7 Answers

Answered By Jacky Flint On

Using LongPathTool makes handling path errors easier.

Answered By Jacky Flint On

I dealt with this recently and Long Path Tool helped get rid of the file.

Answered By FilePathExpert On

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`.

Answered By PowerShellPro On

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.

Answered By PathingGuru77 On

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)`.

Answered By OldSchoolCoder On

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.

Answered By QuickFixFinder On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.