]> git.p6c8.net - dsmonrot.git/blob - dsmonrot.ps1
- Removed the old `net use` lines as they are now saved in the Git
[dsmonrot.git] / dsmonrot.ps1
1 # DSMonRot
2 # Script for rotating Drive Snapshot backups monthly
3 #
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
8 #
9 # Drive Snapshot is copyright by Tom Ehlert
10 # http://www.drivesnapshot.de/
11
12 # Config
13
14 # Path to backup directory
15 [String]$backupDir = "Z:\"
16 # Keep backup for this amount of months (excluding the current month), -1 for indefinite
17 [Int32]$keepMonths = 2
18 # Path to Drive Snapshot
19 [String]$dsPath = "C:\Users\Patrick\Desktop\DSMonRot\snapshot.exe"
20 # Path to Drive Snapshot log file
21 [String]$dsLogFile = "C:\Users\Patrick\Desktop\DSMonRot\snapshot.log"
22 # Disks to backup, see http://www.drivesnapshot.de/en/commandline.htm
23 [String]$disksToBackup = "HD1:1"
24 # Path to DSMonRot log file
25 [String]$logFile = "C:\Users\Patrick\Desktop\DSMonRot\dsmonrot.log"
26
27 # Map network share to this drive letter, comment out if you don't want to use it
28 [String]$smbDrive = "Z"
29 # Path to network share
30 [String]$smbPath = "\\192.168.0.3\ds"
31 # User and password for connecting to network share, comment out if you don't want to use it
32 # (for example if you want to pass current Windows credentials)
33 [String]$smbUser = "patrick"
34 [String]$smbPassword = ""
35
36 # Send an email if an error occured
37 [Boolean]$emailOnError = $True
38 # From address of email notification
39 [String]$emailFromAddress = "alarm@test.local"
40 # To address of email notification
41 [String]$emailToAddress = "patrick@test.local"
42 # Subject of email notification
43 [String]$emailSubject = "DSMonRot"
44 # Mail server
45 [String]$emailMailserver = "localhost"
46 # SMTP Port
47 [Int32]$emailPort = 25
48 # Use SSL?
49 [Boolean]$emailSSL = $False
50 # Use SMTP Auth?
51 [Boolean]$emailAuth = $False
52 # SMTP Auth User
53 [String]$emailUser = ""
54 # SMTP Auth Password
55 [String]$emailPassword = ""
56
57 # End of config
58
59 $dsAdditionalArgs = @("--logfile:$dsLogFile", "--UseVSS")
60
61 # Allow SMTP with SSL and SMTP Auth
62 # see: http://petermorrissey.blogspot.de/2013/01/sending-smtp-emails-with-powershell.html
63 function Send-Email([String]$body) {
64 Write-Host "Sending email: $emailToAddress, $body"
65
66 try {
67 $smtp = New-Object System.Net.Mail.SmtpClient($emailMailServer, $emailPort);
68
69 $smtp.EnableSSL = $emailSSL
70
71 if($emailAuth) {
72 $smtp.Credentials = New-Object System.Net.NetworkCredential($emailUser, $emailPassword);
73 }
74
75 $smtp.Send($emailFromAddress, $emailToAddress, $emailSubject, $body);
76 }
77 catch {
78 Write-Host "Could not send email: $_.Exception.Message"
79 }
80 }
81
82 $errorMessages = @()
83
84 $smbConnected = $False
85 $success = $False
86
87 if($smbDrive) {
88 Try {
89 Write-Host "Connecting network drive"
90
91 if($smbUser -and $smbPassword) {
92 Write-Host "With credentials"
93
94 $secSmbPassword = $smbPassword | ConvertTo-SecureString -asPlainText -Force
95 $smbCredential = New-Object System.Management.Automation.PSCredential($smbUser, $secSmbPassword)
96
97 New-PSDrive -Name $smbDrive -PSProvider "FileSystem" -Root $smbPath -Credential $smbCredential -Persist -ErrorAction Stop
98 }
99 else {
100 Write-Host "Without credentials"
101
102 New-PSDrive -Name $smbDrive -PSProvider "FileSystem" -Root $smbPath -Persist -ErrorAction Stop
103 }
104
105 $smbConnected = $True
106 }
107 Catch {
108 Write-Host "Could not connect to network drive: $_.Exception.Message"
109 exit
110 }
111 }
112
113 if(!(Test-Path $backupDir)) {
114 Write-Host "Directory $backupDir does not exist!"
115 exit
116 }
117
118 $currMonth = Get-Date -format "yyyy-MM"
119 $currDay = Get-Date -format "yyyy-MM-dd"
120
121 Write-Host $currMonth
122
123 $backupTarget = $backupDir + "\" + $currMonth
124 $backupTargetFull = $backupTarget + "\" + "Full"
125
126 $backupTargetDiff = $backupTarget + "\" + "Diff-" + $currDay
127
128 Write-Host $backupTarget
129
130 $isDiff = $False
131
132 if((Test-Path $backupTarget) -and (Test-Path $backupTargetFull) -and (Test-Path "$backupTargetFull\*.hsh")) {
133 Write-Host "Differential backup"
134
135 $isDiff = $True
136
137 if(!(Test-Path $backupTargetDiff)) {
138 Write-Host "Creating directory $backupTargetDiff"
139
140 try {
141 New-Item -ItemType directory -Path $backupTargetDiff -ErrorAction Stop
142
143 $success = $True
144 }
145 catch {
146 Write-Host "Could not create directory $backupTargetDiff`: $_.Exception.Message"
147 exit
148 }
149
150 $dsArgs = @($disksToBackup, "$backupTargetDiff\`$disk.sna", "-h$backupTargetFull\`$disk.hsh") + $dsAdditionalArgs
151 Write-Host $dsPath ($dsArgs -join " ")
152
153 & $dsPath $dsArgs
154
155 if($LastExitCode -ne 0) {
156 Write-Host "Error code: $LastExitCode"
157 }
158 }
159 else {
160 Write-Host "Directory $backupTargetDiff already exists!"
161
162 $errorMessages += "Directory $backupTargetDiff already exists!"
163 }
164 }
165 else {
166 Write-Host "Full backup"
167
168 if(!(Test-Path $backupTarget)) {
169 Write-Host "Creating directory $backupTarget"
170 New-Item -ItemType directory -Path $backupTarget
171 }
172
173 if(!(Test-Path $backupTargetFull)) {
174 Write-Host "Creating directory $backupTargetFull"
175 New-Item -ItemType directory -Path $backupTargetFull
176 }
177
178 $dsArgs = @($disksToBackup, "$backupTargetFull\`$disk.sna") + $dsAdditionalArgs
179 Write-Host $dsPath ($dsArgs -join " ")
180
181 & $dsPath $dsArgs
182
183 if($LastExitCode -ne 0) {
184 Write-Host "Error code: $LastExitCode"
185 }
186
187 $success = $False
188 }
189
190 if($isDiff -eq $False -and $success -eq $True -and $keepMonths -ge 0) {
191 Write-Host "Rotating"
192
193 $keepMonthsCount = $keepMonths
194
195 Get-ChildItem $backupDir -Directory | Where-Object {($_.Name -ne $currMonth) -and ($_.Name -match "^\d{4,}-\d{2}$")} | Sort-Object -Descending |
196 Foreach-Object {
197 Write-Host $_ "=>" $_.FullName
198
199 if($keepMonthsCount -ge 0) {
200 $keepMonthsCount--
201 }
202
203 Write-Host $keepMonthsCount
204
205 if($keepMonthsCount -eq -1) {
206 Write-Host "Deleting $_"
207 Remove-Item -Recurse -Force $_.FullName
208 }
209 }
210 }
211
212 if($smbConnected) {
213 Write-Host "Disconnecting network drive"
214 Remove-PSDrive $smbDrive
215 }
216
217 if($emailOnError -and $errorMessages.Count -gt 0) {
218 Send-Email ("Error:`n"+($errorMessages -join "`n"))
219 }

patrick-canterino.de