'Validating file name input in Powershell
I would like to validate input for file name and check if it contains invalid characters, in PowerShell. I had tried following approach, which works when just one of these character is entered but doesn't seem to work when a given alpha-numeric string contains these characters. I believe I didn't construct regex correctly, what would be the right way to validate whether given string contains these characters? Thanks in advance.
#Validate file name whether it contains invalid characters: \ / : * ? " < > |
$filename = "\?filename.txt"
if($filename -match "^[\\\/\:\*\?\<\>\|]*$")
{Write-Host "$filename contains invalid characters"}
else
{Write-Host "$filename is valid"}
Solution 1:[1]
I would use Path.GetInvalidFileNameChars() rather than hardcoding the characters in a regex pattern, and then use the String.IndexOfAny() method to test if the file name contains any of the invalid characters:
function Test-ValidFileName
{
param([string]$FileName)
$IndexOfInvalidChar = $FileName.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars())
# IndexOfAny() returns the value -1 to indicate no such character was found
return $IndexOfInvalidChar -eq -1
}
and then:
$filename = "\?filename.txt"
if(Test-ValidFileName $filename)
{
Write-Host "$filename is valid"
}
else
{
Write-Host "$filename contains invalid characters"
}
If you don't want to define a new function, this could be simplified as:
if($filename.IndexOfAny([System.IO.Path]::GetInvalidFileNameChars()) -eq -1)
{
Write-Host "$filename is valid"
}
else
{
Write-Host "$filename contains invalid characters"
}
Solution 2:[2]
To fix the regex:
Try removing the ^ and $ which anchor it to the ends of the string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Laurel |
