How To Use PowerShell To Check If A File Exists Using Test-Path | 3 Best Ways

The many methods for using PowerShell to check if a file exists in Powershell are covered in this article. Additionally, you’ll learn how to apply each of these approaches to create better code and outcomes using error-handling logic.

Methods to Use PowerShell to Check if a File Exists using Test-Path

This article provides three ways to use PowerShell to determine whether a file is present. Although the use of these three techniques varies, the idea and purpose are the same. There are three of these:

  1. Get-Item and Get-ChildItem Cmdlet.
  2. Check if file exists using Test-Path Cmdlet.
  3. System.IO.File Class

1. Get-Item and Get-ChildItem Cmdlet. 

The Get-object cmdlet is used to retrieve a folder from a given location. The Get-ChildItem cmdlet, in contrast, retrieves the objects and their children from one or more specified locations. These two cmdlets’ capability does not specifically include a file existence check.

What happens if you try to retrieve a nonexistent folder using Get-object or Get-ChildItem? Each missing file will result in an error. As an example, consider the following commands.

$file = 'D:\temp\XYZ.txt'

Get-Item -Path $file

Get-ChildItem -Path $file

Let’s say there is no D:\temp\XYZ.txt file. Each of the aforementioned commands produces an error. The error message for both commands is the same, as you can see in the sample below.

image 1

The $error automatic variable is not updated when the -ErrorAction Ignore parameter is used to conceal an error.

2. Check if file exists using Test-Path Cmdlet.

You can use the Test-Path cmdlet is used to check whether a path or file exists. The outcome of executing this cmdlet to determine whether a file exists is true or false. The outcome shows if the file is present or not.


The necessary syntax to enable the Test-Path cmdlet to check a file is listed below.

Test-Path -Path <PATH to FILE> -PathType Leaf

Use the code below, for instance, to see if a file with the name D:\XYZ.txt exists. Keep in mind that the -PathType Leaf portion instructs the cmdlet to expressly check for a file rather than a directory.

Test-Path -Path D:\XYZ.txt -PathType Leaf
image 2

If the file exists when you perform the aforementioned command in Windows PowerShell, the outcome will be True. If file does not exist, the outcome would be False,

Making A File If One Does Not Already Exist

The script first checks to see if the file already exists to prevent the “file already exists” issue. The script displays a notification and stops trying to create the file if it already exists.

If you want to alter the file’s output location, be careful to modify the value of the $path variable. Run the script in PowerShell after saving it to test it.

# Full path of the file
$file = 'c:\temp\xyz.txt'

#If the file does not exist, create it.
if (-not(Test-Path -Path $file -PathType Leaf)) {
    try {
        $null = New-Item -ItemType File -Path $file -Force -ErrorAction Stop
        Write-Host "The file [$file] has been created."
    }
    catch {
        throw $_.Exception.Message
    }
}
# If the file already exists, show the message and do nothing.
else {
    Write-Host "Cannot create [$file] because a file with that name already exists."
}

3. System.IO.File Class.

Another method to check if the file exists in this post is the Exists() function of the System.IO.File.NET class. PowerShell’s capability to import and use.NET classes and methods is one of its strengths.

Use the code below to use PowerShell’s Exists() method to see if a file is present.

[System.IO.File]::Exists("PATH")

The procedure described above yields a boolean result of true or false. The target file is present if the result is returned as true. In the absence of the target file, the result returned is false.

image

The command in the example code below checks to see if the file c:\temp\xyz.txt exists.

If the file already exists, updating its contents

This Powershell script adds a fresh GUID value to the text file in order to update it. Only if the file is there does the content change take place. In all other cases, the script displays a message.

If necessary, modify the $file variable’s value for the file path. The script should then be tested in PowerShell.

#Full path of the file
$file = 'c:\temp\XYZ.txt'

# If the file exists, append a new GUID value in the file.
if ([System.IO.File]::Exists($file)) {
    try {
        $newValue = ((New-Guid).Guid)
        Add-Content -Path $file -Value $newValue -ErrorAction STOP
        Write-Host "The file [$file] has been updated with [$newValue]"
     } catch {
        throw $_.Exception.Message
     }    
 }

# If the file does not exist, show a message and do nothing.
 else {
     Write-Host "The file [$file] could not be updated because it does not exist."
 }

The snapshot below shows how the script modified the file after each execution. The [System.IO.File]::Exists() method verified that the file c\:XYZ.txt exists, which prompted the update to take place.