'PowerShell Delete File If Exists

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
}

Thanks for the help! Tom



Solution 1:[1]

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"
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yves Kipondo