Add robust sanitization for names used in paths

Introduces a new common function, `ConvertTo-SafeName`, to sanitize strings by removing characters that are invalid in Windows file paths.

This function is now used consistently when creating directory and file names for drivers (Dell, HP, Lenovo, Microsoft) and applications to prevent path-related errors. It replaces several ad-hoc sanitization methods with a single, more robust implementation.
This commit is contained in:
rbalsleyMSFT
2025-09-16 16:43:43 -07:00
parent 8d7e4d1066
commit cb14e84a26
7 changed files with 40 additions and 12 deletions
@@ -194,4 +194,22 @@ function Set-Progress {
WriteLog "[PROGRESS] $Percentage | $Message"
}
function ConvertTo-SafeName {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$Name
)
# Replace invalid Windows filename characters (<>:"/\|?* and control chars) with a dash
$sanitized = $Name -replace '[<>:\"/\\|?*\x00-\x1F]', '-'
# Collapse multiple consecutive dashes
$sanitized = $sanitized -replace '-{2,}', '-'
# Trim leading/trailing spaces, periods, and dashes
$sanitized = $sanitized.Trim(' ','.','-')
if ([string]::IsNullOrWhiteSpace($sanitized)) {
$sanitized = 'Unnamed'
}
return $sanitized
}
Export-ModuleMember -Function *
@@ -108,11 +108,13 @@ function Get-Application {
# Determine app type and folder path
$appIsWin32 = ($Source -eq 'msstore' -and $AppId.StartsWith("XP"))
$sanitizedAppName = ConvertTo-SafeName -Name $AppName
if ($sanitizedAppName -ne $AppName) { WriteLog "Sanitized app name: '$AppName' -> '$sanitizedAppName'" }
if ($Source -eq 'winget' -or $appIsWin32) {
$appBaseFolderPath = Join-Path -Path "$AppsPath\Win32" -ChildPath $AppName
$appBaseFolderPath = Join-Path -Path "$AppsPath\Win32" -ChildPath $sanitizedAppName
}
else {
$appBaseFolderPath = Join-Path -Path "$AppsPath\MSStore" -ChildPath $AppName
$appBaseFolderPath = Join-Path -Path "$AppsPath\MSStore" -ChildPath $sanitizedAppName
}
# If downloading multiple archs for a Win32 app, create a subfolder