Skip to content

Instantly share code, notes, and snippets.

@lankaapura
Last active March 7, 2018 07:43
Show Gist options
  • Save lankaapura/ff5c8b5f1363de3b11e4993da82f3af1 to your computer and use it in GitHub Desktop.
Save lankaapura/ff5c8b5f1363de3b11e4993da82f3af1 to your computer and use it in GitHub Desktop.
This will replace invalid characters in filename with a placeholder string. This will help to generate unique filenames.
# based on https://stackoverflow.com/a/15121461
Function Replace-InvalidFileNameChars {
param(
[Parameter(Mandatory=$true,
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String]$Name
)
$r = @{
'"' = "-dq-";
'<' = "-gt-";
'>' = "-st-";
'|' = "-pi-";
'*' = "-as-";
'\' = "-bs-";
'/' = "-fs-";
'?' = "-qm-";
'.' = "-dt-";
' ' = "-sp-";
}
$regexes = $r.keys | foreach {[System.Text.RegularExpressions.Regex]::Escape($_)}
$regex = [regex]($regexes -join '|')
$callback = { $r[$args[0].Value] }
return $regex.Replace($Name, $callback)
}
Replace-InvalidFileNameChars "feature/abcdef"
Replace-InvalidFileNameChars "feature/abc|def"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment