Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate file path parameter

Tags:

powershell

param ([ValidateScript({ Test-Path -Path $_ -PathType Leaf })][string]$filePath)

If I declare a parameter like this, will $filePath evaluate to false if it's an invalid path?

Is the point of this to do something like

if($filePath) { /* do stuff... */ }

or will an exception be thrown?

like image 836
filur Avatar asked Nov 13 '15 07:11

filur


1 Answers

You should use the ValidateScript attribute if your function requires a valid path. PowerShell will throw the error for you if the user provides an invalid path. You probably also want to add [Parameter(Mandatory=$true)] otherwise you can omit the $filePathparameter and the function will get called without an exception.

Here is an example:

function This-IsYourFunction 
{
    Param
    (
        [Parameter(Mandatory=$true)]
        [ValidateScript({Test-Path $_})]
        [string]
        $filePath
    )

    Write-Host "Hello, World."
}
like image 92
Martin Brandl Avatar answered Nov 16 '22 19:11

Martin Brandl