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 withif
statement to check if file exists at given location. - If files exists, use
Remove-Item
cmdlet to remove the file at given location.
1 2 3 4 5 6 7 8 9 10 |
$filePath = "C:\test\new.txt" if (Test-Path -Path $filePath){ Remove-Item $filePath Write-Host "$filePath removed successfully." } else{ Write-Host "$filePath not found." } |
Output:
1 2 3 |
C:\test\new.txt removed successfully. |
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.
1 2 3 4 |
Remove-Item $filePath Write-Host "$filePath removed successfully." |
If a file does not exist, it is False
, and the command in the else
block gets executed.
1 2 3 |
Write-Host "$filePath not found." |
Let’s rerun the script to confirm whether the file is deleted.
1 2 3 |
C:\test\new.txt not found. |
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.
1 2 3 4 5 6 7 8 9 10 |
$filePath = "C:\test\readonly.txt" if (Test-Path -Path $filePath){ Remove-Item $filePath -Force Write-Host "$filePath removed successfully." } else{ Write-Host "$filePath not found." } |
That’s it. We hope you have understood how to delete a file if it exists in PowerShell.