Powershell Script – Delete listed files

Some easy-peasy script that will permanently delete files, that are listed in the array:

cls;
$FilePaths = New-Object System.Collections.ArrayList
$FilePaths.add("C:\myfile1.txt") | Out-Null
$FilePaths.add("C:\myfile2.txt") | Out-Null
$FilePaths.add("") | Out-Null
$FilePaths.add("") | Out-Null

$FilePaths | Foreach-Object {
   
    $filePath = $_

    If($filePath) {
        If(Test-Path -Path $filePath){
            Remove-Item $filePath
            Write-Host "Deleted: $filePath"
        } else {
            Write-Host "Not found: $filePath"
        }
    }
}

The Out-Null cmdlet is used to suppress the output, instead of sending it to the console. The ArrayList.Add method always prints the index of the new item that is added and the result would look like this:

0
1
Deleted: C:\myfile1.txt
Deleted: C:\myfile2.txt

Instead of like this (using Out-null):

Deleted: C:\myfile1.txt
Deleted: C:\myfile2.txt

Another version of the script, which deletes all files from selected folder:

$FilesFromDir = Get-ChildItem 'C:\MyFiles\' -Filter "*.txt"

$FilesFromDir | Foreach-Object {
   
    $filePath = $_.FullName

    If($filePath) {
        If(Test-Path -Path $filePath){
            Remove-Item $filePath
            Write-Host "Deleted: $filePath"
        } else {
            Write-Host "Not found: $filePath"
        }
    }
}

Filter cmdlet is used to specify the files for deleting. For example

 -Filter "*.txt"

will select only text files and they will be deleted. If Filter is not set, all content of the directory will be deleted (including subdirectories and files).

Leave a Reply