Share via


How to Use Test-Path in PowerShell Scripts

You can use the Windows PowerShell cmdlet Test-Path to avoid unnecessary errors in your scripts caused by things not being where you expect them, or by another part of your script returning a “path” that isn’t valid.

So, for example, we can test if $profile exists:
   Test-Path $profile 

And if you have a $profile, this returns True, and if you don’t, it returns False. So far, so good. Suppose I want to know if the path for my $profile even exists? Then we can use:
   Test-Path (split-path $profile)

Which will work almost all the time. Where it will give you the wrong answer is if you have a FILE that is where your profile directory ought to be. So, to get around that, we do:  
   Test-Path -pathtype container (Split-Path $profile)

So, how to use Test-Path? Well, as a simple example, I have a standard profile I use on all my machines, but I’m constantly building new virtual machines for specialized test environments. In a new machine, the directory for the $profile doesn’t yet exist, so a simple copy won’t work. Instead, I use:

# First, make sure that u: is mapped to my home directory 
if (! (test-path -isvalid u:\WindowsPowerShell)) {  
    net use  u: \\server\charlie  
} 
# Now, create the $profile directory if  it doesn’t exist
$proDir = (split-path $profile) 
if ( ! (test-path -pathtype container $proDir)) { 
   mkdir $proDir
   cp u:/WindowsPowerShell/* $proDir
} else  { 
   cp u:/ WindowsPowerShell/* $proDir
} 

Notice that first test, using the -isValid switch to Test-Path. The -isValid switch returns True if the path is syntactically correct. And it should return True, since there’s nothing wrong with a “U:\WindowsPowerShell” path syntactically. But here I’m taking advantage of what some consider a bug in Test-Path, but which I think is just the way the file system provider treats it. If a drive doesn’t exist, then test-path -isValid will return False, even if the path would be acceptable if the drive were mapped.

An important warning about using the -isValid switch. If I were to use it on a new machine that didn’t yet have my profile on it, it would still return True, since there’s nothing syntactically wrong with the path. So Test-Path -isValid $profile will always return true.

See Also