如何仅删除众多备份文件夹之一中的特定文件类型 - Powershell

问题描述 投票:0回答:1

我有几台机器,我们将它们命名为A、B、C、D。每个月都会备份机器,备份三个文件夹。为了节省机器内的空间,备份每台机器的三个文件夹后,我需要一个脚本来连接到源机器,并在每台机器的“backup”文件夹中,仅保留“.tgz”文件的最新7个副本作为以及相应的“.txt”文件。其余的tgz和txt文件可以删除。

我不太熟悉 powershell 脚本,需要一些帮助。

我不太熟悉 powershell,并且还没有成功完成任何脚本草案

powershell filter retain
1个回答
0
投票

这是一个带注释的脚本,可以帮助您理解每个步骤

# 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"
            } 
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.