PowerShell-Cleanup_Job_Local_Server_1Days

Create file name “Cleanup_Job_Local_Server_1Days.ps1”

# Parameters

$folderPath = "F:\SQL_DB_Backup\Daily_Backup\FULL"  # Replace with the path to your backup folder

$fileExtension = "*.bak"  # Replace with the file extension of your backup files

$daysOld = 1  # Rece with the number of days to determine the age threshold for deletion

 

# Get the current date

$currentDate = Get-Date

 

# Get a list of files that match the criteria

$files = Get-ChildItem -Path $folderPath -Recurse -Filter $fileExtension

 

# Loop through each file

foreach ($file in $files)

{

    # Calculate the file age

    $fileAge = $currentDate - $file.LastWriteTime

 

    # Check if the file is older than the specified number of days

    if ($fileAge.Days -ge $daysOld)

    {

        try {

            # Remove the file

            Remove-Item -Path $file.FullName -Force

            #Write-Host "Deleted file: $($file.FullName)"

            } catch

                {

            #Write-Host "Failed to delete file: $($file.FullName) - $_"

                }

    }

}

 

Run using below command/Create job step:

powershell.exe -ExecutionPolicy Bypass -File "F:\PowerShell_Script\Cleanup_Job_Local_Server_1Days.ps1"


No comments:

Post a Comment

Popular Posts