Shrinking Paths

Share |

Join PowerShell.com!
Subscribe to Feed

PowerShell eBook
Sign up for
Your PowerTip of the Day:

Award-winning PowerShellPlus


Admin Guide to PowerShell Remoting


Mastering PowerShell eBook

Many file-related .NET Framework methods fail when the overall path length exceeds a certain length. Use low-level methods to convert lengthy paths to the old 8.3 notation which is a lot shorter in many cases:

function Get-ShortPath($Path) {
    $code = @'
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)]
public static extern uint GetShortPathName(string longPath,
StringBuilder shortPath,uint bufferSize);
'@
    $API = Add-Type -MemberDefinition $code -Name Path -UsingNamespace System.Text -PassThru
    $shortBuffer = New-Object Text.StringBuilder ($Path.Length * 2)
    $rv = $API::GetShortPathName( $Path, $shortBuffer, $shortBuffer.Capacity )
    if ($rv -ne 0) {
        $shortBuffer.ToString()
    } else {
        Write-Warning "Path '$path' not found."
    }
}

Here is how you can use the new function:

PS> $null = md c:\thisIsALongName\VeryLongPath\MayExceed260chars -ea 0
PS> Get-ShortPath 'c:\thisIsALongName\VeryLongPath\MayExceed260chars'
c:\THISIS~1\VERYLO~1\MAYEXC~1

Twitter This Tip! ReTweet this Tip!


Posted Mar 30 2012, 06:00 AM by ps1
Copyright 2012 PowerShell.com. All rights reserved.