简体   繁体   中英

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

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

Step 1: You want multiple files. You can do that two ways:

$files = "C:\file1.txt","C:\file2.txt","C:\file3.txt"

That would work, is cumbersome. Easier? Have all files in one.csv list, import that. Remember, the first row is not read, since its consider the header:

$files = Import-Csv "C:\yourcsv.csv"

Alright Step 2: now you got your files, now we want to cycle them:

Foreach ($file in $files) {
If (Test-Path $file) {
Remove-Item $file -verbose | Add-Content C:\mylog.txt }
else { Write-Host "$file not found" }}

Foreach loops take each individual "entry" in one variable and do whatever you want with them. That should do what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM