Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading