PowerShell Basics: Using Test-Path to Check if a File Exists with Examples

PowerShell Basics_ Using Test-Path to Check if a File Exists

PowerShell Test-Path Cmdlet

If there is a problem finding a file, or checking for a container object, then call for PowerShell’s Test-Path; it will respond with a ‘True or False’.

Classic Example:  PowerShell Checks If a File Exist

Start with a simple script to check the existence of your file.

# PowerShell Check If File Exists
$WantFile = "C:\Windows\explorer.exe"
Test-Path $WantFile

Note 1: The only result that PowerShell can return is a true or a false.  However, Test-Path cries out for an ‘if’ statement to act upon the output, thus:-

# PowerShell  Checks If a File Exists
$WantFile = "C:\Windows\explorer.exe"
$FileExists = Test-Path $WantFile
If ($FileExists -eq $True) {Write-Host "Yippee"}
Else {Write-Host "No file at this location"}

Note 2: As with all these scripts, please amend my examples to fit your environment.

Guy Recommends: SolarWinds Wake-On-LAN Utility (FREE TOOL)Solarwinds Wake-On-LAN

Encouraging computers to sleep when they’re not in use is a great idea – until you are away from your desk and need a file on that remote sleeping machine!

WOL also has business uses, for example, rousing machines so that they can have update patches applied.  My real reason for recommending you download this free tool is because it’s so much fun sending those ‘Magic Packets’. Give WOL a try – it’s free.

SolarWinds Wake-On-LAN Download 100% FREE Tool

Test-Path Environmental Variables

In addition to physical file locations, you can also employ Test-Path to interrogate the registry or as here, Environmental Variables.

# PowerShell Test-Path for Environmental Variables
Test-Path env:\PathExt

Challenge: Which of these are really Environment variables?
Public, Private, Temp, Tump and Tmp

PowerShell Test-Path -IsValid

One of the under-rated jobs for Test-Path is to validate that the path part of a script really exists.

# PowerShell script to check a valid path
Clear-Host
$ImageFiles = "H:\Sports\fun_pictures\"
$ValidPath = Test-Path $ImageFiles -IsValid
If ($ValidPath -eq $True) {Write-Host "Path is OK"}
Else {Write-Host "Mistake in ImageFiles variable"}

PowerShell Test-Path -Exclude

Here is a real-life problem, I wanted to see if there were any files which are not .gif, pnp, bmp or .jpg, that have got mixed up with my photo collection.  Assumption: the files I (we) are interested in are stored in H:\Sports\fun_pictures\

# Script to check for rogue picture format.
Clear-Host
$ImageFiles = "H:\Sports\fun_pictures\*.*"
$RogueExists = Test-Path $ImageFiles `
-exclude *.jpg, *.gif, *.png, *.bmp
If ($RogueExists -eq $True) {Write-Host ` "Non .jpg .gif .png .bmp images"}
Else {Write-Host "There are no unknown formats."}

Note 3: You will have to edit the above file radically if you want it to work on your computer.  Change the values for $ImageFiles and also tweak the -exclude file extensions.  See more on PowerShell Else.

Guy Recommends: SolarWinds Engineer’s Toolset (FREE TRIAL)Engineer's Toolset v10

This Engineer’s Toolset provides a comprehensive console of 50 utilities for troubleshooting computer problems.  Guy says it helps me monitor what’s occurring on the network, and each tool teaches me more about how the underlying system operates.

There are so many good gadgets; it’s like having free rein of a sweetshop.  Thankfully the utilities are displayed logically: monitoring, network discovery, diagnostic, and Cisco tools.  Try the SolarWinds Engineer’s Toolset on a 14-day free trial now!

SolarWinds Engineer's Toolset Download 14-day FREE Trial

A Test-Path Example To Make You Think

# PowerShell Test-Path Cmdlet -Exclude
Clear-Host
$WantFile = "C:\Windows\.*"
$FileExists = Test-Path -Path $WantFile -Exclude *.*
If ($FileExists -eq $True) {Write-Host "Yippee"}
Else {Write-Host "No file at this location"}

Note 4: I created this script deliberately.  It makes no sense in practical terms.  Please adjust the value of Exclude *.* to *.exe or *.dll.  As you can see wildcards are allowed in the path an in the extensions.

Note 5: Here I have explicitly used the -Path parameter, however, any value after Test-Path is assumed to be the location, thus  -Path is optional.

Note 6: I often find that experimenting with Get-ChildItem alongside Test-Path reveals the strengths and weaknesses of these two cmdlets.

 

Research The PowerShell Test-Path Cmdlet

# Find out more about PowerShell Test-Path cmdlet
Clear-Host
Get-Help Test-Path -full

Note 7: By interrogating Test-Path with Get-Help we can unearth useful parameters such as -IsValid to check the path.  There are also -Include and -exclude, which refine the contents of your search. It was thanks to Get-Help that I discovered -PathType.

Test-Path -PathType

The main purpose of the -PathType parameter is to check if the object is a file or a folder.  However, it can also be used in the registry to check for keys or data.

Clear-Host
$Location = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon'
Test-Path $Location -PathType container

Trap:  HKLM: needs that colon.  If you simply export areas of the registry, then copy as:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
there are problems.

HKEY_LOCAL_MACHINE is fine, the space between Windows and NT is no problem, but the lack of a colon is a show-stopper, it should be:
HKEY_LOCAL_MACHINE:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon

Guy Recommends:  Network Performance Monitor (FREE TRIAL)Review of Orion NPM v11.5

SolarWinds Network Performance Monitor (NPM) will help you discover what’s happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

What I like best is the way NPM suggests solutions to network problems.  Its also has the ability to monitor the health of individual VMware virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you try NPM on a 30-day free trial.

SolarWinds Network Performance Monitor Download 30-day FREE Trial

The Rest of the Path Family

Here is a simple technique to find more cmdlets.  Get-Command -Noun often throws up interesting results, for example Resolve-Path.

# PowerShell Path Cmdlet Research
Clear-Host
Get-Command -Noun Path
Convert-Path
Join-Path
Resolve-Path
Split-Path
Test-Path

Join-Path Example

Here is a beautiful script to find which drive hosts a particular folder.

Clear-Host
$Folder = "Stuff"
Get-PSDrive | Where-Object {
$_.root -match "[C-Z]:\\" -and (Test-Path $(Join-Path $_.root $Folder))
}

Note 8: Please change “Stuff” to the name of the folder you are looking for.
For example: $Folder = “Program Files”

See more real-life tasks for PowerShell »

Summary of PowerShell Test-Path Cmdlet

The classic job for PowerShell Test-Path is to check that a file exists.  However, you can extend its usefulness by testing registry paths, or to search for files with a particular extension.


See more Microsoft PowerShell tutorials:

PowerShell Home   • Test-ServerHealth  • Test-SystemHealth   • Test-Connection  • Test-Path

PowerShell Logon Script  • PowerShell add printer  • PowerShell Schedule Task  • Free CSVDE Tool

Map Network Drive  • Exchange 2010 PowerShell Cmdlets   • Exchange 2010 Performance Monitor

Please email me if you have a better script examples. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.