2 # Script for rotating Drive Snapshot backups monthly
4 # Author: Patrick Canterino <patrick@patrick-canterino.de>
5 # WWW: https://www.patrick-canterino.de/
6 # https://github.com/pcanterino/dsmonrot
7 # License: 2-Clause BSD License
9 # Drive Snapshot is copyright by Tom Ehlert
10 # http://www.drivesnapshot.de/
14 # Path to backup directory
15 [String]$backupDir = "Z:\"
16 # Keep backup for this amount of months (excluding the current month),
18 [Int32]$keepMonths = 2
19 # Rotate BEFORE the beginning of a full backup (default is after a successful
21 # WARNING: If this option is set to $True and the full backup fails you have
23 $rotateBeforeBackup = $False
24 # Path to Drive Snapshot
25 [String]$dsPath = "C:\Users\Patrick\Desktop\DSMonRot\snapshot.exe"
26 # Path to Drive Snapshot log file (specify only the file name if you set
27 # $dsLogFileToBackup to $True)
28 #[String]$dsLogFile = "C:\Users\Patrick\Desktop\DSMonRot\snapshot.log"
29 [String]$dsLogFile = "snapshot.log"
30 # Set to $True if you want to put the log file of Drive Snapshot into the same
31 # directory as the backup
32 [Boolean]$dsLogFileToBackup = $True
33 # Disks to backup, see http://www.drivesnapshot.de/en/commandline.htm
34 [String]$disksToBackup = "HD1:1"
35 # Path to DSMonRot log file
36 [String]$logFile = "C:\Users\Patrick\Desktop\DSMonRot\dsmonrot.log"
38 # Map network share to this drive letter, comment out if you don't want to use it
39 [String]$smbDrive = "Z"
40 # Path to network share
41 [String]$smbPath = "\\192.168.0.3\ds"
42 # User and password for connecting to network share, comment out if you don't want to use it
43 # (for example if you want to pass current Windows credentials)
44 [String]$smbUser = "patrick"
45 [String]$smbPassword = ""
47 # Send an email if an error occured
48 [Boolean]$emailOnError = $True
49 # From address of email notification
50 [String]$emailFromAddress = "alarm@test.local"
51 # To address of email notification
52 [String]$emailToAddress = "patrick@test.local"
53 # Subject of email notification
54 [String]$emailSubject = "DSMonRot on $env:computername"
56 [String]$emailMailserver = "localhost"
58 [Int32]$emailPort = 25
60 [Boolean]$emailSSL = $False
62 [Boolean]$emailAuth = $False
64 [String]$emailUser = ""
66 [String]$emailPassword = ""
70 $dsAdditionalArgs = @("--UseVSS")
72 # Allow SMTP with SSL and SMTP Auth
73 # see: http://petermorrissey.blogspot.de/2013/01/sending-smtp-emails-with-powershell.html
74 function Send-Email([String]$body) {
75 Write-Host "Sending email: $emailToAddress, $body"
78 $smtp = New-Object System.Net.Mail.SmtpClient($emailMailServer, $emailPort)
80 $smtp.EnableSSL = $emailSSL
83 $smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPassword)
86 $smtp.Send($emailFromAddress, $emailToAddress, $emailSubject, $body)
89 Write-Host "Could not send email: $_.Exception.Message"
93 function Rotate-Backup {
94 if($keepMonths -lt 0) {
100 $keepMonthsCount = $keepMonths
102 Get-ChildItem $backupDir -Directory | Where-Object {($_.Name -ne $currMonth) -and ($_.Name -match "^\d{4,}-\d{2}$")} | Sort-Object -Descending |
104 Write-Host $_ "=>" $_.FullName
106 if($keepMonthsCount -ge 0) {
110 if($keepMonthsCount -eq -1) {
111 Write-Host "Deleting $_"
112 Remove-Item -Recurse -Force $_.FullName
117 Write-Host "Started at" (Get-Date -format "yyyy-MM-dd HH:mm:ss")
121 $smbConnected = $False
126 Write-Host "Connecting network drive"
128 if($smbUser -and $smbPassword) {
129 Write-Host "With credentials"
131 $secSmbPassword = $smbPassword | ConvertTo-SecureString -asPlainText -Force
132 $smbCredential = New-Object System.Management.Automation.PSCredential($smbUser, $secSmbPassword)
134 New-PSDrive -Name $smbDrive -PSProvider "FileSystem" -Root $smbPath -Credential $smbCredential -Persist -ErrorAction Stop
137 Write-Host "Without credentials"
139 New-PSDrive -Name $smbDrive -PSProvider "FileSystem" -Root $smbPath -Persist -ErrorAction Stop
142 $smbConnected = $True
145 Write-Host "Could not connect to network drive $smbDrive`: $_.Exception.Message"
150 if(!(Test-Path $backupDir)) {
151 Write-Host "Directory $backupDir does not exist!"
155 $currMonth = Get-Date -format "yyyy-MM"
156 $currDay = Get-Date -format "yyyy-MM-dd"
158 Write-Host $currMonth
160 $backupTarget = $backupDir + "\" + $currMonth
161 $backupTargetFull = $backupTarget + "\" + "Full"
163 $backupTargetDiff = $backupTarget + "\" + "Diff-" + $currDay
165 Write-Host $backupTarget
169 if((Test-Path $backupTarget) -and (Test-Path $backupTargetFull) -and (Test-Path "$backupTargetFull\*.hsh")) {
170 Write-Host "Differential backup"
174 if(!(Test-Path $backupTargetDiff)) {
175 Write-Host "Creating directory $backupTargetDiff"
178 New-Item -ItemType directory -Path $backupTargetDiff -ErrorAction Stop
183 Write-Host "Could not create directory $backupTargetDiff`: $_.Exception.Message"
187 $dsLogPath = if($dsLogFileToBackup) { "$backupTargetDiff\$dsLogFile" } else { $dsLogFile }
189 $dsArgs = @($disksToBackup, "--logfile:$dsLogPath", "$backupTargetDiff\`$disk.sna", "-h$backupTargetFull\`$disk.hsh") + $dsAdditionalArgs
190 Write-Host $dsPath ($dsArgs -join " ")
194 if($LastExitCode -ne 0) {
195 Write-Host "Drive Snapshot failed to backup! Exit code: $LastExitCode"
196 $errorMessages += "Drive Snapshot failed to backup! Exit code: $LastExitCode"
203 Write-Host "Directory $backupTargetDiff already exists!"
204 $errorMessages += "Directory $backupTargetDiff already exists!"
208 Write-Host "Full backup"
210 if(!(Test-Path $backupTarget)) {
211 Write-Host "Creating directory $backupTarget"
212 New-Item -ItemType directory -Path $backupTarget
215 if(!(Test-Path $backupTargetFull)) {
216 Write-Host "Creating directory $backupTargetFull"
217 New-Item -ItemType directory -Path $backupTargetFull
220 if($rotateBeforeBackup) {
224 $dsLogPath = if($dsLogFileToBackup) { "$backupTargetFull\$dsLogFile" } else { $dsLogFile }
226 $dsArgs = @($disksToBackup, "--logfile:$dsLogPath", "$backupTargetFull\`$disk.sna") + $dsAdditionalArgs
227 Write-Host $dsPath ($dsArgs -join " ")
231 if($LastExitCode -ne 0) {
232 Write-Host "Drive Snapshot failed to backup! Exit code: $LastExitCode"
233 $errorMessages += "Drive Snapshot failed to backup! Exit code: $LastExitCode"
239 if($rotateBeforeBackup -eq $False -and $success -eq $True) {
245 Write-Host "Disconnecting network drive"
248 Remove-PSDrive $smbDrive -ErrorAction Stop
251 Write-Host "Could not disconnect network drive $smbDrive`: $_.Exception.Message"
252 $errorMessages += "Could not disconnect network drive $smbDrive`: $_.Exception.Message"
256 if($emailOnError -and $errorMessages.Count -gt 0) {
257 Send-Email ("Error:`n"+($errorMessages -join "`n"))
260 Write-Host "Ended at" (Get-Date -format "yyyy-MM-dd HH:mm:ss")