Automating File Deletion Using PowerShell and CSV

In many cases, we find ourselves needing to delete files based on specific criteria, such as file type, age, or location. Performing this task manually can be time-consuming and error-prone. However, with PowerShell and a simple Excel or CSV file, we can automate the process and save valuable time. In this blog post, we will explore how to leverage PowerShell to read file deletion criteria from an Excel or CSV file and efficiently delete files that match the specified conditions.

Prerequisites:
To follow along with this tutorial, you'll need the following:

1. A computer running Windows with PowerShell installed.
2. Basic knowledge of PowerShell commands and scripting.
3. An Excel or CSV file containing the file deletion criteria.

Step 1: Prepare the Excel/CSV File
Start by creating an Excel or CSV file that includes the necessary information for deleting files. The following columns are required:

- File Path: The path to the directory where the files are located.
- File Type: The type or extension of the files to be deleted.
- Number of Days Before: The number of days before which the files must have been last modified.
- Files to be Removed from Subfolders or Not: Specify whether to delete files from subfolders as well (Yes/No).

Save the Excel file as `file_criteria.xlsx` or the CSV file as `file_criteria.csv`.

Step 2: Writing the PowerShell Script
Open your favorite text editor and create a new file. Let's name it `DeleteFiles.ps1`. Copy and paste the following PowerShell script into the file:

```powershell
# Read the CSV file
$data = Import-Csv -Path "file_criteria.csv"

# Initialize counters
$totalDeleted = 0
$pathCounters = @{}

# Process each row in the CSV file
foreach ($row in $data) {
    $filePath = $row.'File Path'
    $fileType = $row.'File Type'
    $daysBefore = $row.'Number of Days Before'
    $deleteSubfolders = $row.'Files to be Removed from Subfolders or Not'

    # Check if the file path is valid
    if (Test-Path $filePath -PathType Container) {
        # Define the parameters for the Get-ChildItem cmdlet
        $params = @{
            Path = $filePath
            Filter = "*.$fileType"
            Recurse = $deleteSubfolders -eq 'Yes'
            File = $true
            ErrorAction = 'SilentlyContinue'
            Force = $true
        }

        # Get the files matching the criteria
        $files = Get-ChildItem @params | Where-Object {
            $_.LastWriteTime -lt (Get-Date).AddDays(-$daysBefore)
        }

        # Delete the files
        foreach ($file in $files) {
            Write-Host "Deleting file: $($file.FullName)"
            $file | Remove-Item -Force
            $totalDeleted++
            $pathCounters[$filePath]++
        }
    }
    else {
        Write-Host "Invalid file path: $filePath"
    }
}

# Display the number of files deleted from each path
Write-Host "`nNumber of Files Deleted per Path:`n"
foreach ($path in $pathCounters.Keys) {
    $count = $pathCounters[$path]
    Write-Host "Path: $path - Deleted files: $count"
}

# Display the total number of files deleted
Write-Host "`nTotal Number of Files Deleted: $totalDeleted"
```


This comment is open to all however, use of abusive language is not allowed. Please be respectful to others and share your views with a positive intent.

Post a Comment (0)
Previous Post Next Post