Created
February 6, 2020 09:14
-
-
Save gitfvb/9d9844857b3f0a584cda9057e70c21f9 to your computer and use it in GitHub Desktop.
Daily backup and cleanup for folders in PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################ | |
# | |
# SETTINGS | |
# | |
################################################ | |
$foldersToBackup = @( | |
"D:\Apteco\Publish\holidays\private" | |
"D:\Apteco\Publish\holidays\public" | |
) | |
$timestamp = [datetime]::Now.ToString("yyyyMMddHHmmss") # timestamp for now | |
$logfile = "E:\Apteco\Log\backup_manual.log" # path of the logfile | |
$maxAgeBeforeRemoval = 7 # maximum age for folder in days | |
$removeOldFilesAfterBackup = $true # remove folders older than x days? | |
################################################ | |
# | |
# LOG | |
# | |
################################################ | |
"$( [datetime]::Now.ToString("yyyyMMddHHmmss") )`t-------------------------------" >> $logfile | |
################################################ | |
# | |
# BACKUP AND REMOVAL | |
# | |
################################################ | |
$foldersToBackup | foreach { | |
$source = $_ | |
# mirror the files from D drive to E drive with the same path -> could be changed to another drive or path if wished | |
$destination = $source -replace 'D:\\', 'E:\' | |
# add a timestamp at the destination | |
$destinationWithTimestamp = "$( $destination )\$( $timestamp )\" | |
# make sure the source folder will not be created again | |
$source = "$( $source )\*" | |
# create the new backup folder | |
New-Item -Path $destinationWithTimestamp -ItemType Directory | |
# log | |
"$( [datetime]::Now.ToString("yyyyMMddHHmmss") )`tBackup of ""$( $source )"" to ""$( $destinationWithTimestamp )""" >> $logfile | |
# Copy from source to destination | |
Copy-Item -Path $source -Destination $destinationWithTimestamp -Force -Recurse | |
# remove if needed and older than x days | |
if ( $removeOldFilesAfterBackup ) { | |
[array]( Get-ChildItem $destination -Attributes Directory ) | ForEach { | |
$directoryToCheck = $_ | |
$age = [datetime]::Now - [datetime]::ParseExact($directoryToCheck.Name,"yyyyMMddHHmmss",$null) | |
if ( $age.days -gt $maxAgeBeforeRemoval ) { | |
"$( [datetime]::Now.ToString("yyyyMMddHHmmss") )`tRemoving ""$( $directoryToCheck.FullName )"" because it is ""$( $age.days )"" days old" >> $logfile | |
Remove-Item -Path $directoryToCheck.FullName -Recurse | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment