33

I was able to find how to use the GetInvalidFileNameChars() method in a PowerShell script. However, it seems to also filter out whitespace (which is what I DON'T want).

EDIT: Maybe I'm not asking this clearly enough. I want the below function to INCLUDE the spaces that already existing in filenames. Currently, the script filters out spaces.

Function Remove-InvalidFileNameChars {

param([Parameter(Mandatory=$true,
    Position=0,
    ValueFromPipeline=$true,
    ValueFromPipelineByPropertyName=$true)]
    [String]$Name
)

return [RegEx]::Replace($Name, "[{0}]" -f ([RegEx]::Escape([String][System.IO.Path]::GetInvalidFileNameChars())), '')}

7 Answers 7

53

Casting the character array to System.String actually seems to join the array elements with spaces, meaning that

[string][System.IO.Path]::GetInvalidFileNameChars()

does the same as

[System.IO.Path]::GetInvalidFileNameChars() -join ' '

when you actually want

[System.IO.Path]::GetInvalidFileNameChars() -join ''

As @mjolinor mentioned (+1), this is caused by the output field separator ($OFS).

Evidence:

PS C:\> [RegEx]::Escape([string][IO.Path]::GetInvalidFileNameChars())
"\ \ \|\  \ ☺\ ☻\ ♥\ ♦\ ♣\ ♠\ \\ \t\ \n\ ♂\ \f\ \r\ ♫\ ☼\ ►\ ◄\ ↕\ ‼\ ¶\ §\ ▬\ ↨\ ↑\ ↓\ →\ ←\ ∟\ ↔\ ▲\ ▼\ :\ \*\ \?\ \\\ /
PS C:\> [RegEx]::Escape(([IO.Path]::GetInvalidFileNameChars() -join ' '))
"\ \ \|\  \ ☺\ ☻\ ♥\ ♦\ ♣\ ♠\ \\ \t\ \n\ ♂\ \f\ \r\ ♫\ ☼\ ►\ ◄\ ↕\ ‼\ ¶\ §\ ▬\ ↨\ ↑\ ↓\ →\ ←\ ∟\ ↔\ ▲\ ▼\ :\ \*\ \?\ \\\ /
PS C:\> [RegEx]::Escape(([IO.Path]::GetInvalidFileNameChars() -join ''))
"\| ☺☻♥♦\t\n♂\f\r♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼:\*\?\\/
PS C:\> $OFS=''
PS C:\> [RegEx]::Escape([string][IO.Path]::GetInvalidFileNameChars())
"\| ☺☻♥♦\t\n♂\f\r♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼:\*\?\\/

Change your function to something like this:

Function Remove-InvalidFileNameChars {
  param(
    [Parameter(Mandatory=$true,
      Position=0,
      ValueFromPipeline=$true,
      ValueFromPipelineByPropertyName=$true)]
    [String]$Name
  )

  $invalidChars = [IO.Path]::GetInvalidFileNameChars() -join ''
  $re = "[{0}]" -f [RegEx]::Escape($invalidChars)
  return ($Name -replace $re)
}

and it should do what you want.

4
  • 1
    Thanks so much for explaining and posting a working solution!
    – MKANET
    Commented Apr 14, 2014 at 19:50
  • 4
    The following is a little bit shorter, without sacrifying readability I think. Replacing the last 2 lines with 1: return $Name -replace "[${invalidChars}]",'_'
    – superjos
    Commented Jan 31, 2023 at 19:49
  • 1
    (superjos answer confirmed ps v5.4),"[${invalidChars}]" is a valid RegExp. [RegEX]::Escape() helps with readability but is not necessary for replacement function.
    – dank8
    Commented Oct 21, 2023 at 6:53
  • I had to escape the characters in order to replace the characters in a filename, though the [RegEX]::Escape() didn't escape the backslash and thus didn't replace it. $invalidChars = [IO.Path]::GetInvalidFileNameChars() -join '\' was the solution for me. Commented Aug 13 at 8:11
35

My current favourite way to accomplish this is:

$Path.Split([IO.Path]::GetInvalidFileNameChars()) -join '_'

This replaces all invalid characters with _ and is very human readable, compared to alternatives such as:

$Path -replace "[$([RegEx]::Escape([string][IO.Path]::GetInvalidFileNameChars()))]+","_"
2
  • I'm on Windows and open and close brackets are apparently wildcards? I had to add them to the list. So the above is rewritten as: $Path.Split([IO.Path]::GetInvalidFileNameChars(),@('[',']')) -join '_' Commented Jun 22, 2023 at 6:24
  • @zumalifeguard These wildcards aren't special characters in Windows, but they're special in PowerShell. If the cmdlet you're using accepts LiteralPath instead of Path, you can use square brackets freely.
    – Athari
    Commented Jan 29 at 6:34
10

I suspect it has to do with non-display characters being coerced to [string] for the regex operation (and ending up expressed as spaces).

See if this doesn't work better:

([char[]]$name | where { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''

That will do a straight char comparison, and seems to be more reliable (embedded spaces are not removed).

$name = 'abc*\ def.txt'
([char[]]$name | where { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''

abc def.txt

Edit - I believe @Ansgar is correct about the space being caused by casting the character array to string. The space is being introduced by $OFS.

1
  • Excellent solution, Rob.
    – user189198
    Commented Apr 14, 2014 at 18:28
7

I wanted spaces to replace all the illegal characters so space is replaced with space

$Filename = $ADUser.SamAccountName
[IO.Path]::GetinvalidFileNameChars() | ForEach-Object {$Filename = $Filename.Replace($_," ")}
$Filename = "folder\" + $Filename.trim() + ".txt"
1
  • Easy and clean!
    – tbolender
    Commented Dec 15, 2017 at 12:29
1

Please try this one-liner with the same underlying function.

to match

'?Some "" File Name <:.txt' -match ("[{0}]"-f (([System.IO.Path]::GetInvalidFileNameChars()|%{[regex]::Escape($_)}) -join '|'))

to replace

'?Some "" File Name <:.txt' -replace ("[{0}]"-f (([System.IO.Path]::GetInvalidFileNameChars()|%{[regex]::Escape($_)}) -join '|')),'_'

0

[System.IO.Path]::GetInvalidFileNameChars() returns an array of invalid chars. If it is returning the space character for you (which it does not do for me), you could always iterate over the array and remove it.

> $chars = @()
> foreach ($c in [System.IO.Path]::GetInvalidFileNameChars())
  {
     if ($c -ne ' ')
     {
        $chars += $c
     }
  }

Then you can use $chars as you would have used the output from GetInvalidFileNameChars().

0

Very slightly different, combined, flexible approach. I was finding that GetInvalidFileNameChars() was not getting all the illegal chars for my needs.

$arrInvalidChars = '[]/|\+={}-$%^&*()'.ToCharArray()
$cleanName = 'a[]|\+={9}-$%^&*()\b'
$arrInvalidChars | % { $cleanName = $cleanName.replace($_,'_')}

Returns $cleanName = 'a_______9__________b'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.