Get filename in the case stored on disk?
Here's what I came up with:
function Get-ActualFileName($file) {
$parent = Split-Path $file
$leaf = Split-Path -Leaf $file
$result = Get-ChildItem $parent | where { $_ -like $leaf }
$result.Name
}
The following PowerShell function is based on another developer's elegant solution for C# at https://stackoverflow.com/a/11436327/854680.
Because Get-ChildItem is not used, it is much faster, which makes a difference when calling this function dozens or hundreds of times.
function Get-FileNameTrueCase {
Param (
[parameter(Mandatory=$true)]
[string]
$DirOrFile
)
if (-not ( (Test-Path $DirOrFile -PathType Leaf) -or (Test-Path $DirOrFile -PathType Container) ) ) {
# File or directory not found
return $DirOrFile
}
$TruePath = "";
foreach ($PathPart in $DirOrFile.Split("\")) {
if ($TruePath -eq "") {
$TruePath = $PathPart.ToUpper() + "\";
continue;
}
$TruePath = [System.IO.Directory]::GetFileSystemEntries($TruePath, $PathPart)[0];
}
return $TruePath;
}