How to Use PowerShell to Check if a File Exists [10 Examples]

Photo of author

By Victor Ashiedu

Published

When you write PowerShell scripts, you may encounter multiple scenarios when you need to check if a file or a folder exists. In this guide, I teach you various ways to use the Test-Path command to check if an item exists.

Option 1: Check if a File Exists without Using a Variable

This section teaches you how to run Test-Path command without a variable.

You can run Test-Path as a stand-alone command. Moreover, you can also combine the command with an IF statement to perform additional tasks based on the result of the Test-Path command.

Example 1: Run Test-Path Directly Without a Variable

This sub-section teaches you how to run Test-Path alone (without using the result in an IF statement).

I have a file called processes.txt in E:\reports.

How to Use PowerShell to Check if a File Exists

To check if the file exists, enter the command below in PowerShell and press enter

Test-Path -Path E:\reports\processes.txt

When I pressed, PowerShell returned True, meaning that the file exists.

How to Use PowerShell to Check if a File Exists

However, if I run the same command for a file that does not exists, PowerShell returns False.

How to Use PowerShell to Check if a File Exists

Example 2: Combine Test-Path and IF Statement without a Variable

As I mentioned earlier, after using PowerShell Test-Path to check if a file exists, you can use the result in an IF statement to perform additions tasks.

In this example, I will check if “E:\reports\processes.txt” exists and if it exists, I will copy the file to “C:\reports”. Here is the script that will do the job.

It is recommended to run this command in PowerShell ISE
If (Test-Path -Path E:\reports\processes.txt ) {
Copy-Item -Path E:\reports\processes.txt -Destination C:\reports
}

Here is the result in PowerShell ISE and the file copied in C:\reports

How to Use PowerShell to Check if a File Exists

I can make the script smarter by adding two additional lines.

Write-Host "file copied"

and….

Else {
Write-Host "file does not exist"
}
The first command above displays a message if the file is copied. The second displays a message that the file does not exist.

Here is the modified script…

If (Test-Path -Path E:\reports\processes.txt ) {
Copy-Item -Path E:\reports\processes.txt -Destination C:\reports
Write-Host "file copied"
}
Else {
Write-Host "file does not exist"
}

Option 2: Check if a File Exists Using a Variable

In the last section I showed you how to use PowerShell to check if a file exists without using variables. In this section, I will save the result of Test-Path in a variable. Then, use the variable in an IF statement.

In the example in this section, I want to check if first-file.txt exists in the path shown in the image below. Then, if it exists, I will copy the file to “C:\PS”

How to Use PowerShell to Check If a File Exists with a Variable

In the first steps, I will run the command below:

$fileexists = Test-Path -Path E:\reports\first-file.txt

This command is the same as the last one with one difference – the result of the command is saved in the fileexists variable.

How to Use PowerShell to Check If a File Exists with a Variable

Example 3: Check if a File Exists and Copy it

When I introduced this section, I saved the output of the Test-Path command to the fileexists variable.

$fileexists = Test-Path -Path E:\reports\first-file.txt

In this subsection, I will teach you how to copy the file if it exists. To do this, I will introduce the IF statement with the Copy-Item command.

If ($fileexists ) {
Copy-Item -Path E:\reports\first-file.txt -Destination C:\PS
}

Here is the full script with the combined commands:

$fileexists = Test-Path -Path E:\reports\first-file.txt
If ($fileexists ) {
Copy-Item -Path E:\reports\first-file.txt -Destination C:\PS
}

And here is the script in PowerShell ISE.

Example 4: Check if a File Exists and Delete it

In the last sub-section, you saw how to check if a file exists and copy the file. What if you want to copy the file instead?

If you want to delete the file instead of copying it, replace the Copy-Item command with the Remove-Item command.

Here is the updated script that uses PowerShell “IF” statement to check if a file exists. Then, if it exists, delete it…

$fileexists = Test-Path -Path E:\reports\first-file.txt
 If ($fileexists ) {
 Remove-Item -Path E:\reports\first-file.txt -Force
 }

Example 5: Check if a File Exists Else Exit

In some PowerShell scripting situations, you may want to check if a file exists. Then, if it exists, perform a specified task – like copy or delete the file – otherwise, exit the script.

To achieve this, all you need to do is add the Else block of the If statement.

In the last sub-section, I used this script to delete a file if it exists.

$fileexists = Test-Path -Path E:\reports\first-file.txt
If ($fileexists ) {
Remove-Item -Path E:\reports\first-file.txt -Force
}

If I want the script to exit if the file does not exist, I will modify the script as shown below…

$fileexists = Test-Path -Path E:\reports\first-file.txt
 If ($fileexists ) {
 Remove-Item -Path E:\reports\first-file.txt -Force
 }
Else {
Break
}

Here is the logic of the modified script…

Check if the file, E:\reports\first-file.txt exists. If it exists, delete the file.

However, if the file does not exist, run the command in the Else block of the If statement. In this instance, the command in the Else loop is the word, Break.

Break” tells PowerShell to stop processing the script. You may also add Break on the “If” block of the statement – beneath the Remove-Item command…

$fileexists = Test-Path -Path E:\reports\first-file.txt
 If ($fileexists ) {
 Remove-Item -Path E:\reports\first-file.txt -Force
 Break
 }

Example 6: Check if a File Exists and Not Empty

This is yet another condition common in PowerShell scripting – checking if a file exists and not empty. This may be applicable for log files.

For example, if you have an application that creates and updates log files, you may write a PowerShell script that checks that new log files are updated.

Moving on, to test if a file exists, you use the Test-Path command. However, to check if the file is empty, you need to introduce another command, Get-ChildItem.

In this scenario, you can use the Get-ChildItem command in two ways.

1, if you want to check if a single file is empty, you can run Get-ChildItem command, using the full file path as the Path parameter. 2, alternatively, if you want to check a bunch of files in a folder, use the folder path as the Path parameter.

In this section, I will give an example that checks if a specific file exists and is empty. I will cover the second option in the How To Use PowerShell To Check If A File Exists An A Folder section later in this guide.

In this example, I want to check if the file, first-file.txt and if it is empty.

As I mentioned earlier, the first step is to run the Get-ChildItem command, using the full file path as the Path parameter. To begin, run the command below…

Get-ChildItem -Path E:\reports\first-file.txt

Here is the result of the command. From the result of the command, you can see that the file has a property called Length.

Effectively, the Length property of a file shows the size of the file. Moreover, if a file is empty, the Length will be zero (0).

So, to use PowerShell to check if is Not empty, we will check if the Length is NOT zero (0).

To achieve this, I will modify the last command as shown below…

(Get-ChildItem -Path E:\reports\first-file.txt).Length -ne "0"

Here is the result of the command in PowerShell. In this instance, because the size of my file is 0 (empty), the command returned false.

This means that this file is empty.

But how do we include the bit that tests if the file exists? Glad you asked!

To introduce the logic that uses PowerShell to checks if a file exists and also check that the file is NOT empty, I will combine parts of our previous script and the Get-ChildItem command above.

Here is my modified script…

$fileexists = Test-Path -Path E:\reports\first-file.txt
$checkiffileisempty = (Get-ChildItem -Path E:\reports\first-file.txt).Length -ne "0"
 If (($fileexists -eq $True) -and ($checkiffileisempty -eq $False)) {
Set-Content -Path E:\reports\first-file.txt -Value "This will add some text for this file"
 }

In this modified version of the script, I made the following changes…

  1. In line 2, I saved the Get-ChildItem command that checks if a file is empty – in a variable called $checkiffileisempty.
$checkiffileisempty = (Get-ChildItem -Path E:\reports\first-file.txt).Length -ne "0"
  1. Then, in line 3 I added another condition to the If statement. The condition part of the If the statement was updated to “If (($fileexists -eq $True) -and ($checkiffileisempty -eq $False))”.

    This condition tests if what is saved in $fileexists is True (file exists). Furthermore, it checks if what is saved in $checkiffileisempt is False (file is empty).

    Effectively, PowerShell checks if the Test-Path command that checked if the file path exists is True. Additionally, it also checks if the Get-ChildItem command that checks if the file is NOT empty is False (meaning that the file is empty)
  2. Finally, if both conditions are met, in line 4, PowerShell will execute the command in the {} bracket of the “If” statement.

    In this example, I have this command in the {} bracket of the “If” statement.
Set-Content -Path E:\reports\first-file.txt -Value "This will add some text for this file"

The command adds the text in the Value parameter of Set-Content command.

To test that the script works, copy it to PowerShell ISE and run the script…

Once I ran the script, the file, first-file.txt – that was previously empty – now has some values in it. Additionally, the file size is no longer zero (0)!

Option 3: Check if a File Exists in a Folder

So far this guide has covered multiple scenarios to use PowerShell to check if a file exists.

In this section, I want to dive deep into folders. Specifically, you will learn how to check if a file exists in the current folder or in all subfolders.

Additionally, you will learn how to use PowerShell to check if a file exists in multiple folders. Finally, I will show you how to use a wildcard to check if a file exists.

Example 7: Check if a File Exists in the Current Folder

In this first example, you will learn how to check if a file exists in the current folder – excluding all subfolders.

In this example, I want to check if files with the “.log” file extension exist in the “E:\reports” folder. However, I want to exclude all subfolders.

The first step is to run the Get-ChildItem command. Then, pipe the output to Where-Object and filter by PSIsContainer property.

The PSIsContainer property is a property that defines folders or directories. In the Where-Object command, I specified “$_.PSIsContainer -ne $true”. This command simply says “Do not return any item if its PSIsContainer property is True. This will return only files.

Here is the command…

Get-ChildItem E:\reports | Where-Object {$_.PSIsContainer -ne $true}

The final step is to return the full path of all files with the “.log” extension in the current folder.

Here is the command…

Get-ChildItem E:\reports | Where-Object { ($_.PSIsContainer -ne $true) -and ($_.Extension -eq ".log")}  | Select-Object FullName
From this point, if you want to perform further tasks on the files, you can pipe the output of the last result into a ForEach loop. Then, within the ForEach loop, you can run additional commands.

Example 8: Check if a File Exists in Subfolders

If you want to check if a specific file or files exists in all subfolders, not on the current folder, you need to make slight changes to the Get-ChildItem command.

Specifically, when you pipe the Get-ChildItem command, into Where-Object, you filter Where-Object to return only folders.

(Get-ChildItem E:\reports | Where-Object {$_.PSIsContainer}).FullName

The command returns the full path to all the subfolders in the specified folder…

In the next step, you need to use ForEach statement to iterate through all the folders returned by the last command. Then, within the ForEach statement, run another Get-ChildItem command against each subfolder.

There are three variants of ForEach but, in this example, I will use the ForEach-Object Cmdlet.

(Get-ChildItem E:\reports | Where-Object {$_.PSIsContainer}).FullName | ForEach-Object {
     Get-ChildItem $_ | Where-Object { ($_.Extension -eq ".log")}  | Select-Object Directory, FullName
}

The command displays all log files in the subfolders…

Example 9: Check if a File Exists in the Root and Subfolders

In the last 2 sub-sections, I used the PSIsContainer property to either filter out subfolders, or return only subfolders. In this example, I will eliminate the PSIsContainer property.

However, I will introduce a Get-ChildItem command parameter, called Recurse. The Recurse parameter forces Get-ChildItem to check the specified folder and all its subfolders.

Here is modified script.

(Get-ChildItem E:\reports -Recurse).FullName | ForEach-Object {
     Get-ChildItem $_ | Where-Object { ($_.Extension -eq ".log")}  | Select-Object Directory, FullName
}

The Recurse parameter is introduced in the first Get-ChildItem command. It is not required in the second Get-ChildItem command (within the ForEach-Object block).

Here is the result of the command. This time, the report includes all log files in the top folder and all its subfolders.

Option 4: Check if a File Exists in a Remote Computer

If you want to test if a file exists on a remote computer, you can apply the same principle discussed in all the examples in this guide.

However, you need to introduce a new command called Invoke-Command. Then, within the Invoke-Command command, use its ScriptBlock parameter to specify one of the commands we discussed earlier in this guide.

Another important thing to note is that, you may need to specify a user name and password for an account with the permission to connect to the remote computer.

Additionally, the specified account should have the permission to run the command in the ScriptBlock parameter – on the remote computer.

Finally, use the ComputerName parameter to specify the name of the remote computer.

For your reference, here is the general syntax of the Invoke-Command command.

Invoke-Command -ComputerName -Credential -ScriptBlock {Test-Path}

To read more about the Invoke-Command command, see “References and Further Reading” at the end of this guide.

Conclusion

The primary command you require to test if an item exists using PowerShell is Test-Path. However, I have demonstrated different ways to combine other conditions with this command-let to achieve different results.

Let me know your thoughts about this article by responding to the “Was this page helpful?” question below.

Finally, for more Email tech Itechguides, visit our Windows PowerShell how-to page. You may also find our Work from Home page very helpful.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

2 thoughts on “How to Use PowerShell to Check if a File Exists [10 Examples]”

  1. Hello, I stumbled on your site as I am just learning Powershell. I am the SCCM admin at work and have always used batch files, but I need to up my game. So, if I can pick your brain, I have a question.

    I am trying to create a powershell script that will detect if a program is run out of the Program Files folder or the Program Files (x86) folder. I want to run this with SCCM. If I run it locally, it works. When I run it from SCCM it fails. SCCM places the contents in the C:\Windows\ccmcache folder, but I don’t know how to tell powershell to run from that folder.

    Any help is appreciated. 😉

    Reply
    • Hi Wayne,

      When you run the script in SCCM, you may need to include PowerShell.exe as shown below:

      PowerShell.exe -File .ps1

      If you do this, it should work since the script works outside SCCM. The reason it may not work within SCCM is that SCCm does not know what program to use to run the script.

      Reply

Leave a comment