How to only delete specific file types in one of the many backed up folders - Powershell

30 Views Asked by At

I have a few machines, let's name them A, B, C, D. Every month the machines are backed up and there are three folders that are backed up. To save space within the machines, after backing up the three folders of each machine, I need a script to connect to the source machines and inside each machine's "backup" folder, retain only the latest 7 copies of the ".tgz" files as well as their corresponding ".txt" files. The rest of the tgz and txt files can be deleted.

I am not well versed with powershell script and require some help.

I am not well versed with powershell and have yet to succeed with any script draft

1

There are 1 best solutions below

3
Douda On

Here is a commented script that should help you understand every steps

# Define the list of machines to backup
$Machines = @('MachineA', 'MachineB', 'MachineC', 'MachineD')

# Define the list of folders under your backup folder
$Folders = @('Folder1', 'Folder2', 'Folder3')

# Define the number of backups to retain
$RetentionCount = 7

# Loop through each machine
foreach ($Machine in $Machines) {
    # Define the source path
    # Assuming your backup files are stored in a folder named "backup" on each machine 
    # And accessibles via \\MachineA\backup, \\MachineB\backup, etc.
    $SourcePath = "\\$Machine\backup"

    # Loop through each folder ('Folder1', 'Folder2', 'Folder3')
    foreach ($Folder in $Folders) {
        # Define the folder path
        $FolderPath = "$SourcePath\$Folder"

        # Get the list of backup files
        # Sorting the list by LastWriteTime in descending order, meaning most recently modified files will be at the top
        $BackupFiles = Get-ChildItem $FolderPath -Filter "*.tgz" | Sort-Object -Property LastWriteTime -Descending

        # Loop through each backup file
        $Index = 0
        foreach ($BackupFile in $BackupFiles) {
            # Increment the index
            $Index++

            # Check if the retention count has been exceeded
            if ($Index -gt $RetentionCount) {
                # Delete the backup file
                Remove-Item $BackupFile.FullName -Force
                # If you want to test only uncomment the line below, and comment the line above
                # Write-Host "Should delete $BackupFile"

                # Delete the corresponding text file
                # Assuming your TGZ and TXT files have the same name
                $TextFile = $BackupFile.FullName.Replace('.tgz', '.txt')
                Remove-Item $TextFile -Force
                # If you want to test only uncomment the line below, and comment the line above
                # Write-Host "Should delete $TextFile"
            } 
        }
    }
}