Check file path parameter

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

If I declare such a parameter, will $filePath be evaluated as false if this is an invalid path?

Is the point of doing something like

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

or will an exception be thrown?

+5
source share
1 answer

You should use the ValidateScript attribute if your function requires a valid path. PowerShell will give you an error if the user provides the wrong path. You probably also want to add [Parameter(Mandatory=$true)] , otherwise you can omit the $filePath parameter and the function will be called without exception.

Here is an example:

 function This-IsYourFunction { Param ( [Parameter(Mandatory=$true)] [ValidateScript({Test-Path $_})] [string] $filePath ) Write-Host "Hello, World." } 
+10
source

Source: https://habr.com/ru/post/1235860/


All Articles