---
title: "PowerShell File Existence Validation: Comprehensive Guide"
description: "Learn how to use PowerShell to check if a file exists using Test-Path, Get-Item, and .NET. Boost your IT skills with this in-depth guide."
canonical: "https://adamtheautomator.com/powershell-check-if-file-exists/"
---

# PowerShell File Existence Validation: Comprehensive Guide

> Learn how to use PowerShell to check if a file exists using Test-Path, Get-Item, and .NET. Boost your IT skills with this in-depth guide.

Source: https://adamtheautomator.com/powershell-check-if-file-exists/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![PowerShell File Existence Validation: Comprehensive Guide](https://adamtheautomator.com/wp-content/uploads/2021/01/How-to-use-PowerShell-to-Check-if-a-File-Exists-Examples.jpg)

# PowerShell File Existence Validation: Comprehensive Guide

[![](https://secure.gravatar.com/avatar/9a14f10ff1b1ec7d790d34f5b559e4d3de2d31b172e6ef266dfd8b479174d97b?s=192&d=mm&r=g)June Castillote](https://adamtheautomator.com/author/june/)21 January 20217 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[PowerShell](/tag/powershell/)

Table of Contents

*   [Prerequisites](#h-prerequisites)
*   [Using PowerShell to Check If File Exists](#h-using-powershell-to-check-if-file-exists)
*   [Using Test-Path](#h-using-test-path)
*   [Example: Creating A File If The File Does Not Exist](#h-example-creating-a-file-if-the-file-does-not-exist)
*   [Using Get-Item and Get-ChildItem](#h-using-get-item-and-get-childitem)
*   [Example: Archiving The Existing File And Creating A New File](#h-example-archiving-the-existing-file-and-creating-a-new-file)
*   [Using \[System.IO.File\]::Exists() .NET Method](#h-using-system-io-file-exists-net-method)
*   [Example: Updating The File Contents If The File Exists](#h-example-updating-the-file-contents-if-the-file-exists)
*   [Conclusion](#h-conclusion)

Do you use PowerShell to create, read, update, and delete files? If so, you’ve probably experienced errors when the target files don’t exist or already exist. Lucky for you, there are ways in PowerShell to check if a file exists before doing anything to it.

Not a reader? Watch this related video tutorial!

**_Not seeing the video? Make sure your ad blocker is disabled._**

For example, instead of letting your code create the file right away, it’s better to test that the file already exists. As shown in the screenshot below, you can write better code and achieve clear output.

![Creating a file that already exists](https://adamtheautomator.com/wp-content/uploads/2021/01/Untitled-2021-01-12T151223.662.png)

Creating a file that already exists

In this article, you’ll learn the different ways to use PowerShell to check if a file exists. You’ll also learn how to use each of these ways to produce better code and results with error handling logic.

## Prerequisites

> _Reduce service desk calls & update cache credentials for remote users even off VPN with a self-service password reset solution. [Get a Demo of Specops uReset!](https://specopssoft.com/contact-us/?utm_source=ata&utm_medium=referral&utm_campaign=na_ata&utm_content=mention)_

This article is a how-to guide in which you’ll learn from different examples. And to follow the examples, you will need the following:

*   Code editor. The recommended ones are _[Visual Studio Code](https://code.visualstudio.com/download)_ and _[Atom](https://github.com/atom/atom/releases),_ which work across platforms. You can also use Windows PowerShell ISE if you’re working on a Windows computer.
*   _Windows PowerShell 5.1_ (Desktop) or _PowerShell 7.1 (Core)_. The commands and scripts in this article apply to both PowerShell editions. Whether you’re using Windows, Linux, or macOS, you’ll be fine as long as you have PowerShell installed.

**_Related: [How to Download and Install PowerShell 7 on Windows, Linux, and macOS](https://adamtheautomator.com/powershell-7-upgrade/)_**

## Using PowerShell to Check If File Exists

This article covers three methods with which to use PowerShell to check if a file exists. Using these three methods differ in usage, but the concept and end goal are the same. These three ways are:

*   `Test-Path` Cmdlet.
*   `Get-Item` and [`Get-ChildItem`](https://adamtheautomator.com/get-childitem/) Cmdlet.
*   `System.IO.File` Class.

There will be examples and demos of each of these three methods, including how to use them with error handling.

## Using Test-Path

The first way is the `Test-Path` cmdlet, specifically designed to determine whether a path or file exists. When using this cmdlet to test whether a file exists, the result is _true_ or _false_. The result indicates whether the file exists or not.

Below is the basic syntax to make the `Test-Path` cmdlet work with checking a file.

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

For example, if you need to check such a file with the name _C:\\temp\\important\_file.txt_ exists, use the code below. Note that the `-PathType Leaf` part tells the cmdlet to check for a file and not a directory explicitly.

```powershell
Test-Path -Path C:\temp\important_file.txt -PathType Leaf
```

When you run the command above in PowerShell, the result returns _True_ if the file exists. Otherwise, the result would be _False_, as you can see from the screenshot below.

![Using Test-Path in PowerShell to check if a file exists](https://adamtheautomator.com/wp-content/uploads/2021/01/Untitled-2021-01-12T151320.485.png)

Using Test-Path in PowerShell to check if a file exists

**_Related: [How to Use the PowerShell Test-Path Cmdlet](https://adamtheautomator.com/powershell-test-path/)_**

### Example: Creating A File If The File Does Not Exist

This example is a typical use-case to create files at a specified location. To avoid the “_file already exists”_ error, the script checks if the file already exists before creating it. If the file exists, the script shows a message and does not attempt to make the file anymore.

Copy the code below and save it in a file called _Create-NewFile.ps1_. Make sure to change the value of the `$path` variable should you want to change the file’s output location. After saving the script, run it in PowerShell to test.

```powershell
# Create-NewFile.ps1

# Full path of the file
$file = 'c:\temp\important_file.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."
 }
```

The screenshot below shows the two different outputs. The first is when running the script while the file does not exist. The second is after creating the file, and it already exists.

![Running the PowerShell script to create a file](https://adamtheautomator.com/wp-content/uploads/2021/01/Untitled-2021-01-12T151411.563.png)

Running the PowerShell script to create a file

**_Related: [Back to Basics: How to Run a PowerShell Script](https://adamtheautomator.com/run-powershell-script/)_**

## Using Get-Item and Get-ChildItem

The `Get-Item` cmdlet’s purpose is to _[get the item at a specified location](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-item?view=powershell-7.1)_. In comparison, the `Get-ChildItem` cmdlet is to _[get the items and child items in one or more specified locations](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7.1)_. The functionality of these two cmdlets is not explicitly to check if files exist.

What happens when you use `Get-Item` or `Get-ChildItem` to get an item that does not exist? You’ll get an error for each missing file. Take the commands below as an example.

```powershell
$file = 'c:\temp\important_file.txt'
Get-Item -Path $file
Get-ChildItem -Path $file
```

Suppose the file _c:\\temp\\important\_file.txt_ does not exist. Each of the commands above returns an error. As you can see from the example below, the error message for both commands is the same.

![Using Get-Item and Get-ChildItem in PowerShell to check if a file exists](https://adamtheautomator.com/wp-content/uploads/2021/01/Untitled-2021-01-12T151459.526.png)

Using Get-Item and Get-ChildItem in PowerShell to check if a file exists

### Example: Archiving The Existing File And Creating A New File

In this example, the script uses the `Get-Item` and `Test-Path` cmdlets. The logic of this script is to do the following:

*   Test if the archive folder exists using `Test-Path`.
    *   If the archive folder does not exist, the script creates a new archive folder in this format – `yyyy-MMM-dd_hh-mm-ss-tt`.
    *   Then, the script moves the old file to the archive folder.
*   Test if the file already exists using `Get-Item`.
    *   If the file exists, the script moves it to the archive folder first. Then the script creates the new file in the original location.
    *   If the file does not exist, the script creates the new file.

Copy the code below and save it as _Create-NewFileAfterArchive.ps1_. After saving the script, run it in PowerShell and verify the results.

```powershell
# Create-NewFileAfterArchive.ps1

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

#Full path to the archiving folder
$archiveFolder = "c:\temp\archive_$(get-date -Format 'yyyy-MMM-dd_hh-mm-ss-tt')\"

# If the file exists, move it to the archive folder, then create a new file.
if (Get-Item -Path $file -ErrorAction Ignore) {
    try {
        ## If the Archive folder does not exist, create it now.
        if (-not(Test-Path -Path $archiveFolder -PathType Container)) {
            $null = New-Item -ItemType Directory -Path $archiveFolder -ErrorAction STOP
        }
        ## Move the existing file to the archive.
        Move-Item -Path $file -Destination $archiveFolder -Force -ErrorAction STOP
        Write-Host "The old file [$file] has been archived to [$archiveFolder]"
     } catch {
        throw $_.Exception.Message
     }
 }
 Create the new file
 try {
     $null = New-Item -ItemType File -Path $file -Force -ErrorAction Stop
     Write-Host "The new file [$file] has been created."
 } catch {
    Write-Host $_.Exception.Message
 }
```

> _Tip: The `-ErrorAction Ignore` parameter suppresses the error (will not show in the console) and also does not record the error to the [`$error` automatic variable](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.1#error)_.

In the screenshot below, the first script run created the file _c:\\temp\\important\_file.txt._ The succeeding script executions created a new archive folder each time, moves the existing file to the archive folder, and then creates a new file in _c:\\temp\\important\_file.txt._

![Running a script in PowerShell to check if a file exists using Get-Item](https://adamtheautomator.com/wp-content/uploads/2021/01/Untitled-2021-01-12T151702.346.png)

Running a script in PowerShell to check if a file exists using Get-Item

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

The last method to learn in this article is the _System.IO.File_ .NET class, specifically the `Exists()` method. One of PowerShell’s strengths its ability to import and use .NET classes and methods.

For example, to use `Exists()` method in PowerShell to check if a file exists, use the code below.

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

The above method produces a boolean result – _true_ or _false_. If the result returns _true_, it means that the target file exists. Otherwise, the result returned is _false_ when the target file does not exist.

In the example code below, the command checks for the existence of the file _c:\\temp\\important\_file.txt_.

```powershell
$file = 'c:\temp\important_file.txt'
[System.IO.File]::Exists($file)
```

As you can see from the result below, the result returns true, confirming that the file exists.

![Using System.IO.File class in PowerShell](https://adamtheautomator.com/wp-content/uploads/2021/01/Untitled-2021-01-12T151832.738.png)

Using System.IO.File class in PowerShell

With this .NET method, you can also use [ternary](https://adamtheautomator.com/powershell-ternary/) operations such as the example below. Instead of showing the default true or false results, you may customize the result message with a shorter implementation. However, the [ternary](https://adamtheautomator.com/powershell-ternary/) operator in this example only applies to PowerShell 7+.

```powershell
$file = 'c:\temp\important_file.txt'
[System.IO.File]::Exists($file) ? "The file exists." : "The file does not exist."
```

### Example: Updating The File Contents If The File Exists

This example script updates the text file by appending a new GUID value. However, the content update only happens if the file exists. Otherwise, the script shows a message and does nothing else.

Copy the script below and save it as _Update-FileContents.ps1_. Change the file path value of the `$file` variable if you need to. Then run the script in PowerShell to test.

```powershell
# Update-FileContents.ps1

#Full path of the file
$file = 'c:\temp\important_file.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."
 }
```

You can see in the screenshot below, the script updated the file during each run. The update happened because the `[System.IO.File]::Exists()` method confirmed that the file _c:\\temp\\important\_file.txt_ exists.

In the end, using the command `gc c:\temp\important_file.txt` to read the contents of the file confirmed that the script updated the file with the GUID values.

![Using \[System.IO.File\]::Exists() .NET Method in PowerShell](https://adamtheautomator.com/wp-content/uploads/2021/01/Untitled-2021-01-12T151948.130.png)

Using \[System.IO.File\]::Exists() .NET Method in PowerShell

**_Related: [Using PowerShell Data Types Accelerators to Speed up Coding](https://adamtheautomator.com/powershell-data-types/)_**

## Conclusion

> _Reduce service desk calls & update cache credentials for remote users even off VPN with a self-service password reset solution. [Get a Demo of Specops uReset!](https://specopssoft.com/contact-us/?utm_source=ata&utm_medium=referral&utm_campaign=na_ata&utm_content=mention)_

In this article, you’ve learned that there’s more than one way to use PowerShell to check if a file exists. It is good practice to check the presence of a file before making any file-related modifications.

You’ve learned about using the cmdlets `Get-Item`, `Get-ChildItem`, and `Test-Path`. As well as the `[System.IO.File]::Exists() .NET` method. The examples showed you how to use techniques and how to combine them with error-handling logic.

Stop enduring those error messages. Overcome them by adding code to check if a file exists before any file-related operations. The techniques you’ve learned here only cover the basics, and it’s up to you now to improve upon them.

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-check-if-file-exists%2F&text=PowerShell%20File%20Existence%20Validation%3A%20Comprehensive%20Guide)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-check-if-file-exists%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-check-if-file-exists%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2026/06/26995-troubleshoot-dns-issues-powershell-codex.webp)

### [Troubleshoot DNS Issues with PowerShell](/troubleshoot-dns-issues-powershell/)

Troubleshoot DNS issues with PowerShell by testing name resolution, DNS client settings, cache entries, and network connectivity in a repeatable workflow.

![](https://adamtheautomator.com/wp-content/uploads/2025/10/image_2025-10-24_095322075.png)

### [Migrating from PowerShell 6 to 7.5: Breaking Changes/New Features](/migrating-powershell-6-to-7-5/)

Migrate from PowerShell Core 6 to 7.5: breaking changes, features, and testing tips.

![](https://adamtheautomator.com/wp-content/uploads/2025/06/featured-image-6.png)

### [How to Add Timeouts to Pester Tests with PowerShell Runspaces](/pester-test-timeout-runspaces/)

Prevent Pester tests from hanging indefinitely using PowerShell runspaces. Learn to handle variable scoping, module loading, TestDrive access, and stream capture challenges with timeout protection.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
