Finding long paths with Powershell

If you are working with “get-childitem”, it won’t deal with long paths.

Expect to see the following:

Get-ChildItem : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 chara
cters, and the directory name must be less than 248 characters.

At C:\Dropbox\Powershell\Scripts\get-longpaths.ps1:7 char:26
+ $folders = Get-childitem <<<< $destinationpath -recurse `
+ CategoryInfo : ReadError: (\\server\d$…akistan Branch):String) [Get-ChildItem], PathTooLongException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand

To deal with this, you probably want to get a list of problem folders (obviously you can only get the level where the problem first occurs, not a list of all the items in the problem folder). You can do this using a try{} catch{} structure.

The following code will build a list of folders using get-childitem (which will return pathtoolongexpection errors), but then pass that list to a foreach, which will go through each folder in turn running a get-childitem. This however is in a try{} catch{} structure so the failure will be captured, and the the foreach will move on to the next folder.

Why two runs with get-childitem? Because if we tried using a trap{} on the first one, the script would stop before continuing so we would only get the first long path.

$destinationpath = "\\server\d$\GROUPDATATEST"

Write-Host "Start check"
#Build a list of folders
$folders = Get-childitem $destinationpath -recurse `
	| where {$_.mode -like "d----"} 
Foreach ($folder in $folders){
		$dump = Get-ChildItem $folder.FullName -ErrorAction Stop
	$FolderFullName = $folder.fullname
		Add-Content -Value "$folderFullname" -Path "LongPaths.txt"
Write-Host "Check Done"


Filed under Microsoft, Powershell

3 responses to “Finding long paths with Powershell

  1. Pingback: Modifying data folder permissions with Powershell | Greg's Blog

  2. Ricktor

    thanks for the info.,you could also try long path tool. it helped me with error 1320 in Win 7.,:)

  3. Iggy

    Thanks for script! It works fine if there are not many directories. I have directory which contains more than 1 mil of subdirs and this $folders = Get-childitem $destinationpath -recurse command will take all memory and eternity to execute. Is there any kind of solution to do it “online”? I mean during piping the results of Get-childitem $destinationpath -recurse command?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s