PS: Check File/Folder/Drive/Path/Location Existence

In scripting very often we come across need to dynamically create a path (file/folder), for which you would like to perform a existence check before you attempt to create a folder.

DRIVE existence/availability check:

$drive = ‘Z:’

if (Test-Path -path $drive) {
    write-host "$drive drive exists"
} else {
    write-host "$drive drive does NOT exists"
}

PS C:> if (Test-Path -path Z:) { write-host "Z: drive exists" } else { write-host "Z: drive does NOT exists" }
Z: drive does NOT exists
PS C:>

FILE existence/availability check:

$file= ‘C:TEMPTestFile.txt’
if (Test-Path -path $file) {
    write-host "$file exists"
} else {
    write-host "$file does NOT exists"
}

PS C:> $file= ‘C:TEMPTestFile.txt’
PS C:> if (Test-Path -path $file) { write-host "$file exists" } else { write-host "$file does NOT exists" }
C:TEMPalpha.jpg exists
PS C:> del $file
PS C:> if (Test-Path -path $file) { write-host "$file exists" } else { write-host "$file does NOT exists" }
C:TEMPalpha.jpg does NOT exists
PS C:>

 

FOLDER existence/availability check:

$folder= ‘C:TEMP’
if (Test-Path -path $folder) {
    write-host "$folder exists"
} else {
    write-host "$folder does NOT exists"
}

PS C:> $folder= ‘C:TEMP’
PS C:> if (Test-Path -path $folder) { write-host "$folder exists" } else { write-host "$folder does NOT exists" }
C:TEMP exists
PS C:>

Leave a Reply

Your email address will not be published. Required fields are marked *