Search code examples
.netpowershell.net-5

How to validate a path string?


Is there any function available to validate a path string?

Microsoft documentation at https://learn.microsoft.com/en-us/dotnet/api/system.io.path?view=net-5.0 says that "All Path members that take a path as an argment throw an ArgumentException if they detect invalid path characters."

Should this throw an exception?

PS C:\src\t> [Io.Path]::GetFullPath('C:\sr<|c\t')
C:\sr<|c\t
PS C:\src\t> dotnet --version
5.0.301
PS C:\src\t> $PSVersionTable.PSVersion.ToString()
7.2.0

Solution

  • Since apparently the behavior changed dramatically since PS version 5.1, you may have to rely on a test function of your own..

    Perhaps something like

    function Test-IsValidPath {
        [CmdletBinding()]
        Param(
            [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
            [Alias('FullName')]
            [string]$Path,
            [switch]$MustExist
        )
        # test for invalid characters
        if ($Path.IndexOfAny([System.IO.Path]::GetInvalidPathChars()) -ge 0) { return $false }
        # if the path should exist
        if ($MustExist) { return (Test-Path -LiteralPath $Path) }
        $true
    }
    
    Test-IsValidPath 'C:\sr<|c\t'  # --> False
    

    Of course, you can also create something that would throw exceptions.. For that, please see Which exception should be thrown for an invalid file name?