Test if file exists in powershell -


i can use test-path check whether file name entered exists, i'd avoid producing system error if user hits return , input string blank. thought -erroraction common parameter trick, this:

$configfile = read-host "please specify config. file: " $checkfile = test-path $configfile -erroraction silentlycontinue 

still produces:

test-path : cannot bind argument parameter 'path' because empty string. @ c:\scripts\testparm2.ps1:19 char:31 +         $checkfile = test-path <<<<  $configfile -erroraction silentlycontinue     + categoryinfo          : invaliddata: (:) [test-path], parameterbindingvalidationexception     + fullyqualifiederrorid : parameterargumentvalidationerroremptystringnotallowed,microsoft.powershell.commands.testpathcommand 

do have check string isn't blank or null explicitly?

i'm using powershell v2.0

you can this:

$checkfile = if ("$configfile") {                test-path -literalpath $configfile              } else {                $false              } 

the double quotes prevent false negatives, e.g. in case want test existence of folder named 0.

another option set $erroractionpreference. however, in case need cast result of test-path boolean value, because although exception suppressed cmdlet still doesn't return result. casting $null "return value" bool produces $false.

$oldeap = $erroractionpreference $erroractionpreference = 'silentlycontinue'  $checkfile = [bool](test-path -literalpath $configfile)  $erroractionpreference = $oldeap 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -