0

I am trying to validate a UNC path using a RegEx and having problems failing on disallowed characters. I can use this to validate one or more characters after \, and before an optional additional .

$fileSystemUNCOnly   = '^\\\\.+(\\)?$'
$path = '\\Server'

CLS
if ($path -match $fileSystemUNCOnly) {
    Write-Host 'Good'
} else {
    Write-Host 'Bad'
}

However, if I try to fail on a disallowed character such as | and $path = '\\Server|', it still shows good.

$fileSystemUNCOnly   = '^\\\\[^:\*\?\"<>\|]' 

What am I doing wrong in the disallow?

Gordon
  • 6,257
  • 6
  • 36
  • 89
  • 1
    Looks like you got what you wanted, a negated character class. Insert it into your initial regex. `'^\\\\[^:*?"<>|]+\\?$'` – Wiktor Stribiżew Mar 18 '20 at 08:18
  • 1
    had you thot about testing [A] `.StartsWith('\\')` and then [B] using the dotnet method `[System.IO.Path]::GetInvalidPathChars()` to see if things are valid? ///// you may want to look at this >>> .net - How do I check for illegal characters in a path? - Stack Overflow — https://stackoverflow.com/questions/2435894/how-do-i-check-for-illegal-characters-in-a-path << – Lee_Dailey Mar 18 '20 at 08:40
  • @Lee_Dailey, I had thought about it, but the bigger picture is I am identifying all the different "types" of path, so drive letter folder and file, UNC folder and file, drive letter alone, UNC server alone, registry hive, registry key & registry value, and url. It ends up being easier to look for the valid drive letter, UNC with server, registry hive or URL with domain name as a switch with regex. Plus, I wanted to understand regex better, since they ALWAYS break my brain. :) – Gordon Mar 18 '20 at 08:59
  • That said, what I might do is use that approach in the default of the switch. So when I can't validate a good path, I can try to discern intent (starts with \\ or a-z:) and then test for invalid characters this way, so my final error can actually say exactly what the problem is. – Gordon Mar 18 '20 at 09:03
  • 1
    @Gordon - thank you for the explanation of it all. learning and fun and some usefulness ... a quite nifty combo! the best of good luck to you ... [*grin*] – Lee_Dailey Mar 18 '20 at 09:03

0 Answers0