Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Delete File If Exists

Tags:

powershell

Could you help me with a powershell script? I want to check if multiple files exist, if they exist then delete the files. Than provide information if the file has been deleted or information if the file does not exist.

I have found the script below, it only works with 1 file, and it doesn't give an message if the file doesn't exist. Can you help me adjust this? I would like to delete file c:\temp\1.txt, c:\temp\2.txt, c:\temp\3.txt if they exist. If these do not exist, a message that they do not exist. Powershell should not throw an error or stop if a file doesn't exist.

$FileName = "C:\Test\1.txt"
if (Test-Path $FileName) {
   Remove-Item $FileName -verbose
}
like image 487
Tom Avatar asked Sep 08 '25 11:09

Tom


1 Answers

You can create a list of path which you want to delete and loop through that list like this

$paths =  "c:\temp\1.txt", "c:\temp\2.txt", "c:\temp\3.txt"
foreach($filePath in $paths)
{
    if (Test-Path $filePath) {
        Remove-Item $filePath -verbose
    } else {
        Write-Host "Path doesn't exits"
    }
}
like image 115
Yves Kipondo Avatar answered Sep 10 '25 02:09

Yves Kipondo