# 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-ne0) { $shortPath = $sb.ToString() } else { $shortPath = $null Write-Warning"Shoot. Could not convert $path" }