Jump to page sections

In this little article I describe how to use the cmdlet Test-Path to check if a file exists - as well as a .NET alternative that a coworker once had to use in some SCOM context. Type "Get-Help Test-Path" for more information, possibly with the "-Online" switch. I also quickly demonstrate the .NET class method Exists() from the System.IO.File class.

I also demonstrate how to create a new file if one does not currently exist and show how to handle failures to create the file gracefully.

The official Microsoft online documentation for Test-Path is here at this link.

How To Check If A File Exists With PowerShell

You can use something like this for verification on the command line:
PS C:\> Test-Path C:\Windows
True

Be aware that you need quotes if the path contains spaces, parentheses - and possibly other characters I can't think of now. PowerShell automatically adds quotes when you tab complete. I recommend using single quotes, because double quotes "expand" variables.

This is mostly relevant if you have "$" in the path, partly remediated by logic that makes for instance "C:\$ProgDir\temp" work without having to escape the dollar sign/sigil with "`", the backtick, which is PowerShell's escape character.

PS C:\> Test-Path -Path 'C:\Program Files'
True

Otherwise you will see something like this:

PS C:\> Test-Path C:\Program Files
Test-Path : A positional parameter cannot be found that accepts argument 'Files'.

To explicitly make sure it's a file and not a directory, use the -PathType parameter which has the following possible values:

PS C:\> Test-Path -LiteralPath "C:\Windows\explorer.exe"
True
PS C:\> Test-Path -LiteralPath 'C:\Windows\explorer.exe' -PathType Leaf
True
PS C:\> Test-Path -LiteralPath C:\Windows\explorer.exe -PathType Container
False

Screenshot Example


Script Usage

In a script, you would typically use it in an if statement. To negate and check if the folder or file does not exist, use either "!" or "-not", and remember to enclose the Test-Path statement in parentheses.

Also remember that if the path or file name contains a space, you need to surround the entire path in quotes. Single quotes or double quotes will work the same if there are no "expandable" parts in the path or file name, but the slightly safer choice is single quotes. This is what PowerShell defaults to when you auto-complete names with tab at the prompt.

You should also be made aware of the difference between -Path and -LiteralPath. The latter will take the path literally, as the name indicates, while the former supports wildcard syntax. This is often discovered by accident when someone encounters a file with uneven brackets in it, because it's part of the same syntax -like uses, as in [a-f0-9] for one hex digit. This will cause error messages, at least on earlier versions of PowerShell, when using -Path. When listing directory structures from one root directory, use -LiteralPath. And unless you need wildcard support, it's the safer choice.

PS C:\> if (Test-Path -LiteralPath C:\Windows\explorer.exe -PathType Leaf) { "It's a file/leaf" }
It's a file/leaf

PS C:\> if ( -not (Test-Path -LiteralPath 'C:\Windows\explorer.exe' -PathType Container) ) { "It's not a container/directory/folder" }
It's not a container/directory/folder

PS C:\temp> if (-not (Test-Path -Path '.\FileThatDoesNotExist.html' -PathType Leaf)) {
    # File doesn't exist, so do stuff...
}

Creating A File If It Doesn't Exist

You can, for instance, use the cmdlet Set-Content to create a new file if it doesn't currently exist.

See my examples and Get-Help Set-Content (it has an -Online switch parameter) or Microsoft Docs online here at this link.

You can also use Out-File and other methods I won't bother elaborating here.

Of course you can use a $Variable with the file name in place of the hard-coded text here.

This just creates a file with an empty string as its content.

PS C:\temp> if (-not (Test-Path .\FileThatDoesNotExist.txt -PathType Leaf)) {
     Set-Content -Encoding UTF8 -Path .\FileThatDoesNotExist.txt -Value ""
     Write-Verbose "Created 'FileThatDoesNotExist.txt'." -Verbose
}                                                                    

VERBOSE: Created 'FileThatDoesNotExist.txt'.

PS C:\temp> Get-Content .\FileThatDoesNotExist.txt PS C:\temp>

Or you can do it like this if working on the command line or if it suits your fancy:

"" | Set-Content x:\path\filenamehere.xml

I figured it's good to demonstrate what's likely considered the most proper script usage way first.

If you want to test for failures to create the file, you can use a try {} catch {} statement along with the parameter and value "-ErrorAction Stop" to the cmdlet creating the file, e.g. Set-Content or Out-File.

Here's a quick example:

$FileName = "TestPathArticleFile.txt"

PS C:\temp> if (-not (Test-Path -LiteralPath "$Env:WinDir\$FileName")) {
    
    try {
    
        "test file..." |
            Set-Content -Encoding UTF8 -LiteralPath "$Env:WinDir\$FileName" -ErrorAction Stop
    
    }
    catch {
    
        Write-Error "Unable to create file. The error was $($_.Exception.Message)"
        # Do other stuff if you want.
    
    }
    
    # Do other stuff if you want.

}

Unable to create file. The error was Access to the path 'C:\windows\TestPathArticleFile.txt' is denied. PS C:\temp>

Seeing is believing often (sometimes wrongly, but that's another story), so here's a screen dump from PowerShell ISE running this example stored in a .ps1 script file.


Enumerating Possible PathType Values

A small "trick" to see the possible enumeration values for -PathType is to use one that doesn't exist, like this:

PS C:\> Test-Path C:\Windows -PathType foo
Test-Path : Cannot bind parameter 'PathType'. Cannot convert value "foo" to type
"Microsoft.PowerShell.Commands.TestPathType" due to invalid enumeration values.
Specify one of the following enumeration values and try again.
The possible enumeration values are "Any, Container, Leaf".
At line:1 char:31
+ Test-Path C:\Windows -PathType <<<<  foo
    + CategoryInfo          : InvalidArgument: (:) [Test-Path], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.TestPathCommand

And we notice the part where it says:

The possible enumeration values are "Any, Container, Leaf".

Using The .NET System.IO.File Class Method "Exists"

You can also use the Exists() method from the .NET System.IO.File class:

PS E:\temp> [System.IO.File]::Exists('E:\temp\csv1.csv')
True

In PowerShell, the "System" namespace is optional, so you can simply use "Io.File" as well.

One thing to be aware of, is that with this method, you need a full path. To check if a file is in the current directory with the IO.File Exists() method, you can use something like this, where you would typically use a variable with the file name in place of the here hard-coded "test.ps1":

PS E:\temp> dir .\test.ps1

Directory: E:\temp

Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 09.07.2012 03:51 206 test.ps1 PS E:\temp> [IO.File]::Exists( (Join-Path (Get-Location) 'test.ps1') ) True PS E:\temp> [IO.File]::Exists('test.ps1') False


Powershell      Windows      Programming          All Categories

Google custom search of this website only

Minimum cookies is the standard setting. This website uses Google Analytics and Google Ads, and these products may set cookies. By continuing to use this website, you accept this.

If you want to reward my efforts