Check If File or Folder Path Exist Using PowerShell

In this blog post, we will learn how to use PowerShell to check if a file or folder exists on the system and return a true or false result.

Test-Path

The PowerShell test-path command enables us to check if a path exists or not on a Windows or Linux machine (when using PowerShell 7.x).

Let’s start with a basic path check using the following command.

Test-Path C:\wsl-backup

The results with display in the console as:

Ture

We can also same the result in a variable.

$result = Test-Path C:\wsl-backup

Use in If statement

From experience, this command is handy in if statement, as shown below.

If(Test-Path $path  )
 {
   "Path Exist"
 }
  else{
    "Path does not exist"
  }

Older or Newer

We can also check if the file or folder is older or newer from a specific date. Below, I have a date and time variable, and I’m checking if the path is newer.

$mysate = Get-Date
Test-Path C:\wsl-backup -NewerThan $mysate 

For more information about the test-path command run.

 Get-help test-path  -online

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.