Jump to page sections
- How To Check If A File Exists With PowerShell
- Screenshot Example
- Script Usage
- Creating A File If It Doesn't Exist
- Enumerating Possible PathType Values
- Using The .NET System.IO.File Class Method "Exists"
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
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:
- Any
- Leaf (file)
- Container (directory/folder)
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.ps1Directory: 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
Blog articles in alphabetical order
A
- A Look at the KLP AksjeNorden Index Mutual Fund
- A primitive hex version of the seq gnu utility, written in perl
- Accessing the Bing Search API v5 using PowerShell
- Accessing the Google Custom Search API using PowerShell
- Active directory password expiration notification
- Aksje-, fonds- og ETF-utbytterapportgenerator for Nordnet-transaksjonslogg
- Ascii art characters powershell script
- Automatically delete old IIS logs with PowerShell
C
- Calculate and enumerate subnets with PSipcalc
- Calculate the trend for financial products based on close rates
- Check for open TCP ports using PowerShell
- Check if an AD user exists with Get-ADUser
- Check when servers were last patched with Windows Update via COM or WSUS
- Compiling or packaging an executable from perl code on windows
- Convert between Windows and Unix epoch with Python and Perl
- Convert file encoding using linux and iconv
- Convert from most encodings to utf8 with powershell
- ConvertTo-Json for PowerShell version 2
- Create cryptographically secure and pseudorandom data with PowerShell
- Crypto is here - and it is not going away
- Crypto logo analysis ftw
D
G
- Get rid of Psychology in the Stock Markets
- Get Folder Size with PowerShell, Blazingly Fast
- Get Linux disk space report in PowerShell
- Get-Weather cmdlet for PowerShell, using the OpenWeatherMap API
- Get-wmiobject wrapper
- Getting computer information using powershell
- Getting computer models in a domain using Powershell
- Getting computer names from AD using Powershell
- Getting usernames from active directory with powershell
- Gnu seq on steroids with hex support and descending ranges
- Gullpriser hos Gullbanken mot spotprisen til gull
H
- Have PowerShell trigger an action when CPU or memory usage reaches certain values
- Historical view of the SnP 500 Index since 1927, when corona is rampant in mid-March 2020
- How Many Bitcoins (BTC) Are Lost
- How many people own 1 full BTC
- How to check perl module version
- How to list all AD computer object properties
- Hva det innebærer at særkravet for lån til sekundærbolig bortfaller
I
L
M
P
- Parse openssl certificate date output into .NET DateTime objects
- Parse PsLoggedOn.exe Output with PowerShell
- Parse schtasks.exe Output with PowerShell
- Perl on windows
- Port scan subnets with PSnmap for PowerShell
- PowerShell Relative Strength Index (RSI) Calculator
- PowerShell .NET regex to validate IPv6 address (RFC-compliant)
- PowerShell benchmarking module built around Measure-Command
- Powershell change the wmi timeout value
- PowerShell check if file exists
- Powershell check if folder exists
- PowerShell Cmdlet for Splitting an Array
- PowerShell Executables File System Locations
- PowerShell foreach loops and ForEach-Object
- PowerShell Get-MountPointData Cmdlet
- PowerShell Java Auto-Update Script
- Powershell multi-line comments
- Powershell prompt for password convert securestring to plain text
- Powershell psexec wrapper
- PowerShell regex to accurately match IPv4 address (0-255 only)
- Powershell regular expressions
- Powershell split operator
- Powershell vs perl at text processing
- PS2CMD - embed PowerShell code in a batch file
R
- Recursively Remove Empty Folders, using PowerShell
- Remote control mom via PowerShell and TeamViewer
- Remove empty elements from an array in PowerShell
- Remove first or last n characters from a string in PowerShell
- Rename unix utility - windows port
- Renaming files using PowerShell
- Running perl one-liners and scripts from powershell
S
- Sammenlign gullpriser og sølvpriser hos norske forhandlere av edelmetall
- Self-contained batch file with perl code
- Silver - The Underrated Investment
- Simple Morningstar Fund Report Script
- Sølv - den undervurderte investeringen
- Sort a list of computers by domain first and then name, using PowerShell
- Sort strings with numbers more humanely in PowerShell
- Sorting in ascending and descending order simultaneously in PowerShell
- Spar en slant med en optimalisert kredittkortportefølje
- Spre finansiell risiko på en skattesmart måte med flere Aksjesparekontoer
- SSH from PowerShell using the SSH.NET library
- SSH-Sessions Add-on with SCP SFTP Support
- Static Mutual Fund Portfolio the Last 2 Years Up 43 Percent
- STOXR - Currency Conversion Software - Open Exchange Rates API