Home > Enterprise >  How to validate a path string?
How to validate a path string?

Time:11-15

Is there any function available to validate a path string?

Microsoft documentation at https://docs.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

CodePudding user response:

Method 1:

We have ValidateScript command to validate the folder path inside the powershell function parameter like below:

function Validate-Path{
   param(
      [parameter(Mandatory)]
      [String]$Path
   )
   if(Test-Path $Path) {Write-Output "Path is valid"}
   else{Write-Output "Path is invalid"}
}

Give this code in the PowerShell and press enter. And type Validate-Path -Path <give-your-folder-path> and press enter which shows valid or invalid path.

I have executed this to validate my folder path in PowerShell: Look at this image (https://i.imgur.com/BHDg1HO.png)

Method 2:

I also tested the zett42 comment and it worked fine:

PS C:\Users\saiha> Test-Path "C:\Users\saiha\Documents"
True
PS C:\Users\saiha> Test-Path "C:\Users\saiha\Docs"
False
PS C:\Users\saiha>

Also With the given path in a question tested with both the methods:

PS C:\Users\saiha> Test-Path "C:\sr<|c\t"
Test-Path : Illegal characters in path.
At line:1 char:1
  Test-Path "C:\sr<|c\t"
  ~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidArgument: (C:\sr<|c\t:String) [Test-Path], ArgumentException
      FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.TestPathCommand

False
PS C:\Users\saiha> Test-Path "C:\src\t"
True
//User-Defined function
PS C:\Users\saiha> function Validate-Path{
>>    param(
>>       [parameter(Mandatory)]
>>       [String]$Path
>>    )
>>    if(Test-Path $Path) {Write-Output "Path is valid"}
>>    else{Write-Output "Path is invalid"}
>> }
PS C:\Users\saiha> Validate-Path -Path C:\src\t
Path is valid
PS C:\Users\saiha> Validate-Path -Path C:\sr<|c\t
c\t : The module 'c' could not be loaded. For more information, run 'Import-Module c'.
At line:1 char:28
  Validate-Path -Path C:\sr<|c\t
                             ~~~
      CategoryInfo          : ObjectNotFound: (c\t:String) [], CommandNotFoundException
      FullyQualifiedErrorId : CouldNotAutoLoadModule

PS C:\Users\saiha>

Practical Screenshot: https://i.imgur.com/ahTsSG3.png

Correct me If I understood in a different.

In Method 1, I created a user-defined function and tested using it and in method 2, Test-Path is a native function. But both do the same checks and give the correct result.

CodePudding user response:

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?

  • Related