PowerShell – How to Delete a File if it Exists

In this short tutorial I will show how to check if a file exists, and then delete a file if it exists using PowerShell. This can be useful if you are wanting to remove a particular temporary file or maybe a lock file, or maybe you want to use it to clean up some files after running the main part of a script.

Regardless of the reason, it’s easy to check for and remove a file if it exists using PowerShell. In this example, I will be using the test-path cmdlet and the remove-item cmdlet.

PowerShell Script to Check if File Exists before Deleting

Let’s break down the code required. First of all, we will set a value for a variable called FileName. This will be the full path to the file we wish to check for and delete. To set the variable:

$FileName = "c:\scripts\file.txt"

We can now use the test-path cmdlet to check if the file exists or not:

test-path $filename
True

If the file exists the test-path cmdlet returns a true value. OK, so now we have our filename and a way to check if it exists. Next we need to create a condition so that if test-path returns true, then the file is deleted. We can do so using an IF statement:

if (Test-Path $FileName = True) {
  Remove-Item $FileName
}

So, this is my final script, with some output text to show what has happened:

$FileName = "C:\scripts\file.txt"

if (Test-Path $FileName) {
  Remove-Item $FileName
  write-host "$FileName has been deleted"
}

else {
  Write-host "$FileName doesn't exist"
}

Now let’s save it as filecheck.ps1 then try running it a couple of times:

As you can see, the first time the script ran, it checked for and deleted the file once it had confirmed it existed. The second time it ran, it couldn’t find the file as it had already been deleted, so returned the ‘doesn’t exist’ message.

And that’s it! A quick and easy way to check if a file exists and then delete it using PowerShell.

Related posts

Mastering the Linux ifconfig Command

Docker Exec Command With Practical Examples

Debugging with Git Bisect

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More