Home » PowerShell Tips » PowerShell – Check If File Exists

PowerShell – Check If File Exists

While doing file based operation in script file, its very common practice one should follow to check if file exists on specified location or not. If file doesn’t exists then it may throws exception in script while trying to access file ,delete file ,read file or any kind of file based operation.

In PowerShell, there are different ways to check if file exists before doing any file operation to avoid exception.

In this article, I will explain you about how to check if file exists using different ways in PowerShell with examples.

There are four different ways to check if file exists as below

  • Using Test-Path
  • Using Get-Item
  • Using Get-ChildItem
  • Using [System.IO.File]::Exists(file)

Lets understand each of the method to check if a file exists

Using Test-Path to Check if File Exists

PowerShell Test-Path cmdlet check if file exists or not. If file exists then it will return $True. If path or file is missing or doesn’t exists, it will return $False.

Test-Path cmdlet Syntax

Test-Path -Path <FilePath> -PathType Leaf

In the above syntax,

FilePath – file location

Leaf – Check for file and not directory

Test-Path Examples

Let’s consider an example to understand how to use PowerShell Test-Path cmdlet to check if file exists or not.

We want to delete Employee.xlsx file from location. Run below code to understand Test-Path cmdlet

$FileName = "D:\PowerShell\Employee.xlsx"
if (Test-Path $FileName) {
    Write-Host "File Exists"
    #Perform file based operation.. If file exists then delete file
    Remove-Item $FileName
}
else
{
    Write-Host "File Doesn't Exists"
}

In the above PowerShell script,

$FileName variable contains Employee.xlsx file path

Using Test-Path cmdlet, it first check if files exists on location. If file exists then delete file using Remove-Item cmdlet.

If file doesn’t exists then print message on console as “File Doesn’t Exists”

Cool Tip: How to delete folder if exists in PowerShell!

PowerShell Get-Item to Check If a File Exists

PowerShell Get-Item cmdlet used to get item at a specified location. You can use wildcard character (*) to get all the contents of item. We will see how to use Get-Item cmdlet to check file exists or not.

Get-Item Syntax

Get-Item
   [-Path] <String[]>
   [-Filter <String>]
   [-Include <String[]>]
   [-Exclude <String[]>]
   [-Force]
   [-Credential <PSCredential>]
   [-Stream <String[]>]
   [<CommonParameters>]

In the above Get-Item syntax, you can use different parameters to get specific items.

Lets understand, using Get-Item cmdlet to check file exists in PowerShell.

Get-Item Example

Let’s consider an example to delete Employee.xlsx file available at a specified directory. Using PowerShell Get-Item cmdlet to check if file exists or not with below command

$FileName = "D:\PowerShell\Employee.xlsx"

if(Get-Item -Path $FileName -ErrorAction Ignore)
{
   
        Write-Host "File Exists"
        #Perform file based operation, if file exists then delete file
        Remove-Item $FileName
}
else
{
    Write-Host "File Doesn't Exists"
}

In the above PowerShell script,

$FileName variable contains Employee.xlsx file path

Using Get-Item cmdlet, it first check if files exists on location. If file exists then delete file using Remove-Item cmdlet.

If file doesn’t exists then print message on console as “File Doesn’t Exists”.

Cool Tip: How to get file creation date in PowerShell!

PowerShell Get-ChildItem to Check If File Exists

PowerShell Get-ChildItem cmdlet used to get items or child items from one or more specified location. We will see with example, how to use Get-ChildItem cmdlet to check file exists or not.

You can read here to get filename without extension in PowerShell.

Get-ChildItem Syntax

Get-ChildItem
   [[-Path] <string[]>]
   [[-Filter] <string>]
   [-Include <string[]>]
   [-Exclude <string[]>]
   [-Recurse]
   [-Depth <uint32>]
   [-Force]
   [-Name]
   [-Attributes <FlagsExpression[FileAttributes]>]
   [-FollowSymlink]
   [-Directory]
   [-File]
   [-Hidden]
   [-ReadOnly]
   [-System]
   [<CommonParameters>]

In the above Get-ChildItem syntax, you can use different parameters to get items from one or more specific location specified by Path parameter.

Lets understand, using Get-ChildItem cmdlet to check file exists in PowerShell.

Cool Tip: How to use base64 encode file in PowerShell!

Get-ChildItem Example

Let’s consider an example to delete Employee.xlsx file available at a specified location. Using PowerShell Get-ChildItem cmdlet to check if file exists or not with below command

$FileName = "D:\PowerShell\Employee.xlsx"

if(Get-ChildItem -Path $FileName -ErrorAction Ignore)
{
    Write-Host "File Exists"
    #Perform file based operation
}
else
{
    Write-Host "File Doesn't Exists"
}

In the above PowerShell script,

$FileName variable contains Employee.xlsx file path

Using Get-ChildItem cmdlet, it first check if files exists on location. If file exists then delete file using Remove-Item cmdlet.

If file doesn’t exists then print message on console as “File Doesn’t Exists”

-ErrorAction ignore parameter ignore the exception raised while checking file exists operation.

Cool Tip: How to find large size files in PowerShell!

Using [System.IO.File]::Exists() Method

Using .Net class System.IO.FIle and Exists() method, we can check if file exists or not before doing any operation.

Let’s understand using [System.IO.File]::Exists() method with example.

For example, if you want to create a new file at specified location. Before you create new file, you first check if file exists or not to avoid below error

New-Item : The file 'D:\PowerShell\FileCreateExample.txt' already exists.
At line:2 char:1
+ New-Item $FileName -ItemType File
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (D:\PowerShell\FileCreateExample.txt:String) [New-Item], IOException
    + FullyQualifiedErrorId : NewItemIOError,Microsoft.PowerShell.Commands.NewItemCommand

[System.IO.File]::Exists() method takes filename as input and return True or False depends on file exists or not.

$FileName = "D:\PowerShell\FileCreateExample.txt"

if([System.IO.File]::Exists($FileName))
{
    Write-Host "File Exists"
}
else
{
    Write-Host "File Doesn't Exists"
    New-Item $FileName -ItemType File
}

In the above PowerShell script,

$FileName – contains filename path

Using [System.IO.File]::Exists() method to check if file exists. It returns true if file exists else return false.

In case , if file doesn’t exists, you can create new file using New-Item cmdlet.

Cool Tip: How to list files in directory in PowerShell!

Conclusion

In the above article, I have explained four different method to check if file exists using PowerShell way. These methods are Test-Path , Get-Item, Get-ChildItem and [System.IO.File]::Exists().

Its good practice to check if file exists before you perform any file based operation to avoid error. Using file exists check, you can handle errors and condition to do file operation.

You can read more about using PowerShell mkdir to create new directory or New-Item cmdlet to create directory if not exists and pass multiple parameters to function to create directory.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on ShellGeek home page.