Skip to content

Instantly share code, notes, and snippets.

@sba923
Last active January 31, 2024 14:49
Show Gist options
  • Save sba923/54a260dbd0fcd6672de13cf9e81b41db to your computer and use it in GitHub Desktop.
Save sba923/54a260dbd0fcd6672de13cf9e81b41db to your computer and use it in GitHub Desktop.
Resolve path to short (8.3) version
# this is one of Stéphane BARIZIEN's public domain scripts
# the most recent version can be found at:
# https://gist.github.com/sba923/54a260dbd0fcd6672de13cf9e81b41db#file-resolve-shortpath-ps1
param([Parameter(Mandatory = $true)][string] $Path)
# derived from https://devblogs.microsoft.com/scripting/use-powershell-to-display-short-file-and-folder-names/
$item = Get-Item -Path $Path -ErrorAction SilentlyContinue
if ($null -eq $item)
{
Write-Error ("Cannot find path '{0}' because it does not exist." -f $Path)
$null
Exit(1)
}
if ($item.PSProvider.Name -ne 'FileSystem')
{
Write-Error ("Only filesystem paths are supported")
$null
Exit(1)
}
$fso = New-Object -ComObject Scripting.FileSystemObject
function GetShortPath([string] $Path)
{
$item = Get-Item -LiteralPath $Path -Force
if ($item.PSIsContainer)
{
if ($item.PSParentPath -eq '')
{
return $item.FullName
}
$shortname = $fso.getfolder($item.FullName).ShortName
$parentpath = Split-Path -Path $Path -Parent
return (Join-Path -Path (GetShortPath -Path $parentpath) -ChildPath $shortname)
}
else
{
$shortname = $fso.getfile($item.FullName).ShortName
$parentpath = Split-Path -Path $Path -Parent
return (Join-Path -Path (GetShortPath -Path $parentpath) -ChildPath $shortname)
}
}
# get a PathInfo object for the item, then clone it so we're able to set the DefaultDisplayPropertySet
$resolvedpath = (Resolve-Path -Path $Path) | Select-Object -Property *
# compute the full short path i.e. short name for each of the path components
$shortpath = GetShortPath -Path $Path
# add ShortPath property
Add-Member -InputObject $resolvedpath -MemberType NoteProperty -Name ShortPath -Value $shortpath
# set the default property to 'ShortPath'
# derived from https://learn-powershell.net/2013/08/03/quick-hits-set-the-default-property-display-in-powershell-on-custom-objects/
#Give this object a unique typename
$resolvedpath.PSObject.Typenames.Insert(0, 'ResolvedShortPath')
#Configure a default display set
$defaultDisplaySet = 'ShortPath'
#Create the default property display set
$defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet('DefaultDisplayPropertySet', [string[]]$defaultDisplaySet)
$PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
$resolvedpath | Add-Member MemberSet PSStandardMembers $PSStandardMembers
# output the final object
$resolvedpath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment