Converting File Paths to 8.3 (Part 2)

by Oct 19, 2020

In the previous post we explained how you can use an old COM component to convert default long path names to short 8.3 path names. While that’s OK for occasional conversions, using COM components is slow and resource intense.

A “cleaner” way would be to use Windows API calls directly. Here is how you can access the internal method that converts long file paths to short ones:

# this is the long path to convert
$path = "C:\Program Files\PowerShell\7\pwsh.exe"

# signature of internal API call
$signature = '[DllImport("kernel32.dll", SetLastError=true)]
public static extern int GetShortPathName(String pathName, StringBuilder shortName, int cbShortName)'
# turn signature into .NET type
$type = Add-Type -MemberDefinition $signature -Namespace Tools -Name Path -UsingNamespace System.Text

# create empty string builder with 300-character capacity
$sb = [System.Text.StringBuilder]::new(300)
# ask Windows to convert long path to short path with a max of 300 characters
$rv = [Tools.Path]::GetShortPathName($path, $sb, 300)

# output result
if ($rv -ne 0)
    $shortPath = $sb.ToString()
    $shortPath = $null
    Write-Warning "Shoot. Could not convert $path"

"Short path: $shortPath"

Twitter This Tip! ReTweet this Tip!