Skip to content

Instantly share code, notes, and snippets.

@dallin
Created January 9, 2019 00:09
Show Gist options
  • Save dallin/46695a46c1d5072a5669d5a2827ff5d2 to your computer and use it in GitHub Desktop.
Save dallin/46695a46c1d5072a5669d5a2827ff5d2 to your computer and use it in GitHub Desktop.
# Created by Dallin Hitchcock on January 8, 2019
# Backs up $SourceDirectory or individual files that have been created since midnight
# Creates a zip file of the backups (name format yyyy-MM-dd.zip)
# Copies the zip file to $DestinationDirectory
# If the $KeepLast parameter is specified, only keeps that number of backups in $DestinationDirectory
param (
[Parameter(Mandatory,ValueFromPipelineByPropertyname)]
[ValidateNotNullOrEmpty()]
[string]$SourceDirectory,
[Parameter(Mandatory,ValueFromPipelineByPropertyname)]
[ValidateNotNullOrEmpty()]
[string]$DestinationDirectory,
[Parameter(Mandatory,ValueFromPipelineByPropertyname)]
[ValidateNotNullOrEmpty()]
[string]$TempStore,
[Parameter(ValueFromPipelineByPropertyname)]
[ValidateNotNullOrEmpty()]
[int]$KeepLast,
[Parameter(ValueFromPipelineByPropertyname)]
[ValidateNotNullOrEmpty()]
[string]$FileTypeFilter
)
Import-Module .\Send-SlackErrorMessage.ps1 -Force
function Backup-Folder {
Try
{
$ZipName = (Get-Date).ToString("yyyy-MM-dd") + ".zip"
# Do the backup
if (Test-Path $TempStore) { Remove-Item $TempStore -Recurse -Force }
New-Item -ItemType Directory -Path $TempStore
if ($FileTypeFilter) {
# Copy all files in source directory that have been created today
$BackupFiles = Get-ChildItem $SourceDirectory -Filter $FileTypeFilter -Recurse | Where-Object { $_.CreationTime -gt [datetime]::Today }
foreach ($ChildFile in $BackupFiles) { Copy-Item -Path $ChildFile.FullName -Destination $TempStore }
}else {
# Whole directory recursive copy
Copy-Item -Path $ChildFile.FullName -Destination $TempStore -Recurse
}
# Create the zip file in $DestinationDirectory
Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::CreateFromDirectory($TempStore, "$DestinationDirectory$ZipName")
# Remove the temp files
Remove-Item $TempStore -Recurse -Force
if ($KeepLast) {
# Only keep the most recent $KeepLast number of backups
Get-ChildItem $DestinationDirectory -Filter *.zip | Sort-Object LastWriteTime -Descending | Select-Object -Skip $KeepLast | Remove-Item -Force
}
}
Catch
{
$ErrorMessage = $_.Exception.Message
Send-SlackErrorMessage $ErrorMessage
Break
}
if (!$?) {
# The operation failed with a non-PowerShell exception
Send-SlackErrorMessage "The operation failed with exit code: $LASTEXITCODE"
}
}
Backup-Folder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment