Delete File If Exists in PowerShell

This tutorial will discuss how to delete a file if it exists using PowerShell.

Delete File If Exists in PowerShell

To delete a file if exists in PowerShell:

  • Use Test-Path cmdlet with if statement to check if file exists at given location.
  • If files exists, use Remove-Item cmdlet to remove the file at given location.

Output:

First, we stored the file path in a variable $filePath. Then we used the Test-Path command as a conditional expression in the if statement.

Test-Path checks whether all elements of the specified path exist. If all elements exist, it returns True. If not, it returns False.

As file exists at given location, it evaluated to True, and Remove-Item removed a file and printed the output.

Remove-Item is cmdlet used for delete one or more items. It can remove many different types of items, including files, folders, registry keys, variables, aliases, and functions.

If a file does not exist, it is False, and the command in the else block gets executed.

Let’s rerun the script to confirm whether the file is deleted.

As you can see, it returned another output because the file is already removed and no longer exists.

Delete Read-only File If Exists in PowerShell

By default, Remove-Item does not delete a hidden or read-only file. To remove such a file, we must use the -Force parameter.

That’s it. We hope you have understood how to delete a file if it exists in PowerShell.

Was this post helpful?

Leave a Reply

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