Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources: Active Threads
Viewing all articles
Browse latest Browse all 8411

Long File Paths

$
0
0

The MAX_PATH for Windows is 260 characters, really 259 because the <NULL> character at the end. At my company there are some users who have files and directories that they cannot open because the file path is too long. In order to find and suggest how to fix the problem for them I thought "Oh! Powershell! I can do it in a couple lines of code." Because Powershell should be able to scan the several TB of data and find all paths longer than 259 characters. Knowing where some long paths were located at I started scripting the script. First, I wanted to test "get-childitem X:\L\O\N\G\P\A\T\H\ -recurse" on a directory with files that cannot be opened due to a long path. What did Powershell return? It did not return the files with a Long Path. It just skipped over them. I tried listing the size of the directory in Powershell and comparing that to Windows Explorer. Different sizes. Oh, No! Powershell doesn't list or even recognize long paths. So I used a combination of MS-DOS inside a Powershell script to find the long paths. This seemed to work great. Wish I could have done it in Powershell though. Why is the would would MS-DOS list the long paths and not Powershell. Is it a bug in the .NET? Here is my script. I know, ugly. Any suggestions for improvements?

$cnt = 0
$arg_cnt=0
foreach ($arg in $args){
    Write-Host ("Checking `"$arg`" ")
    $err_cnt=0
    $paths = New-Object System.Collections.ArrayList
    $arg_cnt++
   
    $y = (Get-Date).Year
    $m = (Get-Date).Month
    $d = (Get-Date).Day
    if($d-le9){
        $d = "0" + $d
    }
    if($m-le9){
        $m = "0" + $m
    }
    if(!(Test-Path ("C:\lngpth\"+$arg[0]+"drive_"+$y+"_"+$m+"_"+$d+"\"))){
        New-Item -Path "C:\lngpth\" -type directory -Name ($arg[0]+"drive_"+$y`
        +"_"+$m+"_"+$d)
    }
   
    $errtxt = ("C:\lngpth\"+$arg[0]+"drive_"+$y+"_"+$m+"_"+$d+"\bigerr_ptlarg"`
    +$arg_cnt+"_"+$y+"_"+$m+"_"+$d+".txt")
   
    cmd /C "dir `"$arg`" /a:-d /s /b 2> $errtxt" | ForEach-Object {if($_.length-gt`
    259){$err_cnt=$paths.add($_);Write-Host($_);}$cnt++;write-host($cnt)}
    $arg[0]
    date >> $errtxt
    $err_cnt++
   
    $optn = ("C:\lngpth\"+$arg[0]+"drive_"+$y+"_"+$m+"_"+$d+"\"+$err_cnt+"ptlarg"`
    +$arg_cnt+"_"+$y+"_"+$m+"_"+$d+".txt")
   
    $ate = date
    $ate = [string]$ate
    $ate > $optn
    $paths >> $optn
    Write-Host ([string]($paths.count)+" long paths found in `"$arg`"")
    Write-Host "$($cnt) files scanned"
}


Viewing all articles
Browse latest Browse all 8411

Trending Articles