Home > Blockchain >  How can I determine if a string is a correctly formatted path regardless of whether it actually exis
How can I determine if a string is a correctly formatted path regardless of whether it actually exis

Time:10-20

I am creating a function and I want to validate that a string passed in to my function is a correctly formatted path. Test-Path determines if the path exists, which I don't want. Is there a RegEx expression that can do this? Or some other native Cmdlet?

Thanks.

CodePudding user response:

You can use Test-Path -IsValid to check for valid but non-existent paths:

Test-Path -LiteralPath 'C:\Whatever' -IsValid

The catch though, is that "valid" doesn't seem to mean the same thing as "correctly formatted".

For example, if I use D:\Whatever it's also valid on my machine, while E:\Whatever is not; because there is no such PSDrive (but C and D exist).

Also strange, WSman:\whatever is False while HKCU:\whatever is True.

It does seem to think UNC paths are valid.

If you're going to look at trying to validate a path another way, you could start with the set of invalid characters, which you can get with [System.IO.Path]::InvalidPathChars.

But here's something weird too, one of those characters is §, and yet C:\§whatever returns True from Test-Path -IsValid.

I'm probably raising more questions than answers here.


From comments:

I'm looking to validate a fully qualified path with drive letter and possible directories. "C:\SomeDirectory\ or D:\blah\blah"

I think the most straightforward thing to do here may be to first check if the path "is rooted", and then to cast it as a [DirectoryInfo] object:

if ([System.IO.Path]::IsPathRooted($path)) {
    # this will throw an exception if the path can't be used
    # for example Z:\whatever is accepted, ZZ:\whatever is not
    $validatedPath = ([System.IO.DirectoryInfo]$path).FullName
}
else {
    throw [System.ArgumentException]"Only fully-qualified paths are accepted."
}

You could also choose to keep the [DirectoryInfo] object rather than "converting" it back to a string with .FullName, as that object has a number of useful properties and methods, even if the directory doesn't exist.

$path = 'Z:\whatever' -as [System.IO.DirectoryInfo]

$path | Format-List *
$path | Get-Member
  • Related