DEV Community

taijidude
taijidude

Posted on

Parameter Validation and Files

Happy new year! This week I learned something about how to handle parameter validation in a powershell script. I'm working on a deployment script where I need to handle file and folder paths.
I passed those paths as a parameter and needed to validate it.

Here is what i learned:

Check if you have an absolute path:

param (
    [ValidateScript({
        if(-Not([System.IO.Path]::IsPathRooted($_))) {
            throw "Not an absolute path!"
        }       
        return $true
    })]
    [string]$path
)
$path
Enter fullscreen mode Exit fullscreen mode

Here i use a .NET Library Method from the System.IO.Path class.
Read more about it here:

https://riptutorial.com/powershell/example/17158/calling--net-library-methods

Check if the path exists:

param (
    [ValidateScript({
        if( -Not(Test-Path $_)) {
            throw "The path doesn't exist!"
        }       
        return $true
    })]
    [string]$path
)
$path
Enter fullscreen mode Exit fullscreen mode

Check if the parameter path is a file:

param (
    [ValidateScript({
        if( -Not(Test-Path $_ -PathType Leaf)) {
            throw "The parameter path has to point to a file!"
        }       
        return $true
    })]
    [string]$path
)
$path
Enter fullscreen mode Exit fullscreen mode

Check if the parameter path is a folder:


param (
    [ValidateScript({
        if( -Not(Test-Path $_ -PathType Container)) {
            throw "The parameter path has to point to a folder!"
        }       
        return $true
    })]
    [string]$path
)
$path
Enter fullscreen mode Exit fullscreen mode

Validate that the path has no illegal characters:

I have seen other articles on the net where the writer suggests to set the parameter type of the path to System.IO.Path to make sure it doesn't contain any illegal characters.

Example:

param (
    [System.IO.Path]$path
)
$path
Enter fullscreen mode Exit fullscreen mode

I disagree with this approach as it makes the function more difficult to handle as you have to make sure that you are passing file paths and not Strings anymore. Something like this will not work:

function test {
    param (
        [System.IO.Path]$path
    )
    $path
}     
$toTest = @(D:\temp, D:\backup)
foreach($item in $toTest) {
    test -path $item
}
Enter fullscreen mode Exit fullscreen mode

My suggestion would be to keep the String type of the parameter and use the -isValid Parameter of the Test-Path function. Something that looks like this:

param (
    [ValidateScript({
        if(-Not(Test-Path $_  -isValid)) {
            throw "The Parameter may not contain the following characters: "+([IO.Path]::GetInvalidFileNameChars() -Join '')
        }
    })]
    [String]$path
)
$path
Enter fullscreen mode Exit fullscreen mode

It keeps the usage of these explicit .NET calls in your validation script and you are still able to pass paths in string arrays to the function.

Top comments (0)