Advertisement
mOjO_mOjO

Remove-InvalidFileNameChars

Jul 16th, 2019
484
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function Remove-InvalidFileNameChars {
  2.     <#
  3.     .SYNOPSIS
  4.     Removes characters from a string that are not valid in Windows file names.
  5.    
  6.     .DESCRIPTION
  7.     Remove-InvalidFileNameChars accepts a string and removes characters that are invalid in Windows file names.
  8.     It then outputs the cleaned string. By default the space character is ignored, but can be included using the RemoveSpace parameter.
  9.     The Replacement parameter will replace the invalid characters with the specified string.
  10.     The Name parameter can also clean file paths. If the string begins with "\\" or a drive like "C:\",
  11.     it will then treat the string as a file path and clean the strings between "\". This has the side effect of removing
  12.     the ability to actually remove the "\" character from strings since it will then be considered a divider.
  13.  
  14.     .PARAMETER Name
  15.     Specifies the file name to strip of invalid characters.
  16.    
  17.     .PARAMETER Replacement
  18.     Specifies the string to use as a replacement for the invalid characters.
  19.    
  20.     .PARAMETER RemoveSpace
  21.     The RemoveSpace parameter will include the space character (U+0032) in the removal process.
  22.    
  23.     .INPUTS
  24.     System.String
  25.     Remove-InvalidFileNameChars accepts System.String objects in the pipeline.
  26.    
  27.     Remove-InvalidFileNameChars accepts System.String objects in a property Name from objects in the pipeline.
  28.    
  29.     .OUTPUTS
  30.     System.String
  31.    
  32.     .EXAMPLE
  33.     PS C:\> Remove-InvalidFileNameChars -Name "<This /name \is* an :illegal ?filename>.txt"
  34.     Output: This name is an illegal filename.txt
  35.    
  36.     This command will strip the invalid characters from the string and output a clean string.
  37.     .EXAMPLE
  38.     PS C:\> Remove-InvalidFileNameChars -Name "<This /name \is* an :illegal ?filename>.txt" -RemoveSpace
  39.     Output: Thisnameisanillegalfilename.txt
  40.    
  41.     This command will strip the invalid characters from the string and output a clean string, removing the space character (U+0032) as well.
  42.     .EXAMPLE
  43.     PS C:\> Remove-InvalidFileNameChars -Name '\\Path/:|?*<\With:*?>\:Illegal /Characters>?*.txt"'
  44.     Output: \\Path\With\Illegal Characters.txt
  45.    
  46.     This command will strip the invalid characters from the path and output a valid path. Note: it would not be able to remove the "\" character.
  47.     .EXAMPLE
  48.     PS C:\> Remove-InvalidFileNameChars -Name '\\Path/:|?*<\With:*?>\:Illegal /Characters>?*.txt"' -RemoveSpace
  49.     Output: \\Path\With\IllegalCharacters.txt
  50.    
  51.     This command will strip the invalid characters from the path and output a valid path, also removing the space character (U+0032) as well. Note: it would not be able to remove the "\" character.
  52.     .EXAMPLE
  53.     PS C:\> Remove-InvalidFileNameChars -Name "<This /name \is* an :illegal ?filename>.txt" -Replacement +
  54.     Output: +This +name +is+ an +illegal +filename+.txt
  55.    
  56.     This command will strip the invalid characters from the string, replacing them with a "+", and outputting the result string.
  57.     .NOTES
  58.     Author: Chris Carter
  59.     Version: 1.3
  60.     Last Updated: January 6, 2016
  61.    
  62.     .Link
  63.     System.RegEx
  64.     .Link
  65.     about_Join
  66.     .Link
  67.     about_Operators
  68.     #>
  69.  
  70.     # Requires -Version 2.0
  71.     [CmdletBinding(HelpURI='https://gallery.technet.microsoft.com/scriptcenter/Remove-Invalid-Characters-39fa17b1')]
  72.  
  73.     Param(
  74.         [Parameter(Mandatory=$true,Position=0,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true)][String]$Name,
  75.         [Parameter(Position=1)][String][Alias('r')]$Replacement='',
  76.         [switch]$RemoveSpace
  77.     )
  78.  
  79.     Begin {
  80.         #Get an array of invalid characters
  81.         $arrInvalidChars = [System.IO.Path]::GetInvalidFileNameChars()
  82.  
  83.         #Cast into a string. This will include the space character
  84.         $invalidCharsWithSpace = [RegEx]::Escape([String]$arrInvalidChars)
  85.  
  86.         #Join into a string. This will not include the space character
  87.         $invalidCharsNoSpace = [RegEx]::Escape(-join $arrInvalidChars)
  88.  
  89.         #Check that the Replacement does not have invalid characters itself
  90.         if ($RemoveSpace) {
  91.             if ($Replacement -match "[$invalidCharsWithSpace]") {
  92.                 Write-Error "The replacement string also contains invalid filename characters."; exit
  93.             }
  94.         }
  95.         else {
  96.             if ($Replacement -match "[$invalidCharsNoSpace]") {
  97.                 Write-Error "The replacement string also contains invalid filename characters."; exit
  98.             }
  99.         }
  100.  
  101.         Function Remove-Chars($String) {
  102.             #Replace the invalid characters with a blank string(removal) or the replacement value
  103.             #Perform replacement based on whether spaces are desired or not
  104.             if ($RemoveSpace) {
  105.                 [RegEx]::Replace($String, "[$invalidCharsWithSpace]", $Replacement)
  106.             }
  107.             else {
  108.                 [RegEx]::Replace($String, "[$invalidCharsNoSpace]", $Replacement)
  109.             }
  110.         }        
  111.     }
  112.  
  113.     Process {
  114.         foreach ($n in $Name) {
  115.             #Check if the string matches a valid path
  116.             if ($n -match '(?<start>^[a-zA-z]:\\|^\\\\\?\\UNC\\|^\\\\\?\\[a-zA-z]:\\|^\\\\)(?<path>(?:[^\\]+\\)+)(?<file>[^\\]+)$') {
  117.                 #Split the path into separate directories
  118.                 $path = $Matches.path -split '\\'
  119.  
  120.                 #This will remove any empty elements after the split, eg. double slashes "\\"
  121.                 $path = $path | Where-Object {$_}
  122.                 #Add the filename to the array
  123.                 $path += $Matches.file
  124.  
  125.                 #Send each part of the path, except the start, to the removal function
  126.                 $cleanPaths = foreach ($p in $path) {
  127.                                 Remove-Chars -String $p
  128.                             }
  129.                 #Remove any blank elements left after removal.
  130.                 $cleanPaths = $cleanPaths | Where-Object {$_}
  131.                
  132.                 #Combine the path together again
  133.                 $Matches.start + ($cleanPaths -join '\')
  134.             }
  135.             else {
  136.                 #String is not a path, so send immediately to the removal function
  137.                 Remove-Chars -String $Name
  138.             }
  139.         }
  140.     }
  141. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement