-
Notifications
You must be signed in to change notification settings - Fork 0
/
My Backup.ps1
335 lines (284 loc) · 10.8 KB
/
My Backup.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#******************************************************************************
#*
#* Module Name: My Backup.ps1
#*
#* Abstract: This is a template PowerShell Script file generated by Reflect.
#* Modify to add your own functionality if required.
#*
#* Returns: 0 - Success.
#* 1 - Error: Invalid XML.
#* 2 - Error: Backup failed.
#* 3 - Error: Not elevated (script will try to execute elevated).
#*
#******************************************************************************
Param([switch]$s, [switch]$full, [switch]$inc, [switch]$diff, [String]$freq, [String]$g)
$strReflectPath = "C:\program files\macrium\reflect\reflectbin.exe";
$strXmlFilePath = "C:\Users\jimlo\OneDrive\Documents\Reflect\My Backup.xml";
$strScriptPath = $MyInvocation.MyCommand.Definition;
#******************************************************************************
#* Func: OnXmlValidationError
#*
#* Desc: Called when a backup fails due to an XML validation error.
#* This is here to be modified for your own uses.
#*
#******************************************************************************
function OnXmlValidationError()
{
Write-Warning " ! XML invalid ($strXmlFilePath).";
# Handle invalid XML error...
}
#******************************************************************************
#* Func: OnBackupError
#*
#* Desc: Called when a backup fails.
#* This is here to be modified for your own uses.
#*
#******************************************************************************
function OnBackupError()
{
Write-Warning " ! Backup failed ($strXmlFilePath).";
# Handle backup error...
}
#******************************************************************************
#* Func: OnBackupSuccess
#*
#* Desc: Called when a backup succeeds.
#* This is here to be modified for your own uses.
#*
#******************************************************************************
function OnBackupSuccess()
{
Write-Host "Starting"
Write-Log -Message "In OnBackupSuccess()" -Level "INFO"
$localDirectoryForTokenFile = "C:\mytemp\to_upload"
$remoteDirectoryForTokenFile = "uploads/"
$tokenFileName = CreateLocalTokenFile
$localPathAndFileNameForTokenFile = Join-Path -Path $localDirectoryForTokenFile -ChildPath $tokenFileName
$remotePath = $remoteDirectoryForTokenFile
Write-Host "localPathAndFileNameForTokenFile=$localPathAndFileNameForTokenFile"
Write-Host "remotePath$remotePath=$remotePath"
SendTokenFile "$tokenFileName" "$remotePath"
}
#******************************************************************************
#* Func: Main
#*
#* Desc: This is main function to start execution.
#*
#******************************************************************************
function Main()
{
Write-Host 'PowerShell script for Macrium Reflect Backup Definition File';
Write-Host "BDF: $strXmlFilePath";
Elevate;
$iExitCode = Backup;
Write-Host "Script finished with exit code $iExitCode.";
Exit $iExitCode;
}
#******************************************************************************
#* Func: Elevate
#*
#* Desc: Elevates this script for UAC.
#* This means that only one UAC Elevation prompt is displayed and
#* functions/programs will not fail if they require admin privileges.
#*
#******************************************************************************
function Elevate()
{
# Only elevate if not ran from the task scheduler.
Write-Host ' * Checking elevated access rights... ' -NoNewLine;
if (-Not $s)
{
# Check to see if we are currently running "as Administrator"
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator"))
{
$ElevatedProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$strType = GetBackupTypeParameter;
$strFreqency = GetFrequencyParameter;
$strGuid = GetGuidParameter;
$ElevatedProcess.Arguments = "-ExecutionPolicy Bypass & '" + $script:MyInvocation.MyCommand.Path + "' $strType $strFreqency $strGuid";
# Indicate that the process should be elevated
$ElevatedProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($ElevatedProcess);
# Exit this unelevated script with exit code for "Error: Not elevated"
Exit 3;
}
}
Write-Host 'Done.';
}
#******************************************************************************
#* Func: Backup
#*
#* Desc: Calls Reflect.exe passing an XML BDF as a parameter.
#*
#******************************************************************************
function Backup()
{
Write-Host ' * Running the backup... ' -NoNewLine;
$strType = GetBackupTypeParameter;
$strFreqency = GetFrequencyParameter;
$strGuid = GetGuidParameter;
$strArgs = "-e -w $strType `"$strXmlFilePath`" $strFreqency $strGuid";
$iResult = (Start-Process -FilePath $strReflectPath -ArgumentList $strArgs -PassThru -Wait).ExitCode;
Write-Host 'Done.';
switch ($iResult)
{
2 { OnXmlValidationError; break; }
1 { OnBackupError; break; }
0 { OnBackupSuccess; break; }
}
return $iResult;
}
#******************************************************************************
#* Func: GetBackupTypeParameter
#*
#* Desc: Determines the backup type from command line parameter...
#* "-full": Full backup
#* "-inc" : Incremental backup
#* "-diff": Differential backup
#*
#******************************************************************************
function GetBackupTypeParameter()
{
if ($full -eq $true) { return '-full'; };
if ($inc -eq $true) { return '-inc'; };
if ($diff -eq $true) { return '-diff'; };
return ''; # Clone
}
#******************************************************************************
#* Func: GetFrequencyParameter
#*
#* Desc: Gets the Schedule Frequency...
#* "-once"
#* "-daily"
#* "-intradaily"
#* "-weekly"
#* "-monthly"
#* "-event"
#*
#******************************************************************************
function GetFrequencyParameter()
{
if ($freq -eq 'once') { return '-freq once'; };
if ($freq -eq 'daily') { return '-freq daily'; };
if ($freq -eq 'intradaily') { return '-freq intradaily'; };
if ($freq -eq 'weekly') { return '-freq weekly'; };
if ($freq -eq 'monthly') { return '-freq monthly'; };
if ($freq -eq 'event') { return '-freq event'; };
return '';
}
#******************************************************************************
#* Func: GetGuidParameter
#*
#* Desc: Gets the Schedule guid
#*
#******************************************************************************
function GetGuidParameter()
{
return '-g ' + $g;
}
#My Custom Stuff
# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
function CreateLocalTokenFile {
param (
[string] $localTokenFileDirectory,
$hour = $null,
[string]$dayName = $null
)
Write-Host "Parms: hour=$hour dayName=$dayName\n"
$fullBackupToken = "full_backup_complete.txt"
$incrementalBackup1Token = "incremental_backup1_complete.txt"
$incrementalBackup2Token = "incremental_backup2_complete.txt"
$incrementalBackup3Token = "incremental_backup3_complete.txt"
if ($null -eq $hour) {
$currentHour = (Get-Date).Hour
Write-Log -Message "Retreiving actual hour from Get-Date: $currentHour" -Level "INFO"
} else {
Write-Log -Message "Hour was received as a parameter: $hour" -Level "INFO"
$currentHour = $hour
}
if ($null -eq $dayName) {
$currentDayOfWeek = (Get-Date).DayOfWeek
} else {
$currentDayOfWeek = $dayName
}
Write-Log -Message "currentHour=$currentHour" -Level "INFO"
switch ($currentDayOfWeek) {
'Monday' {
if ($currentHour -eq 9) { $tokenFileName = $fullBackupToken }
else { $tokenFileName = "unknown_backup_complete_a.txt" }
}
Default {
switch ($currentHour) {
11 { $tokenFileName = $incrementalBackup1Token }
14 { $tokenFileName = $incrementalBackup2Token }
23 { $tokenFileName = $incrementalBackup3Token }
Default { $tokenFileName = "unknown_backup_complete_b.txt" }
}
}
}
$currentDate = Get-Date -Format "yyyyMMdd"
$childPath ="${currentDate}_$tokenFileName"
$fullname = "C:\mytemp\to_upload\$childPath"
#Remove if it already exists so we get the run creation time.
Remove-Item -Path $fullname -Force -ErrorAction SilentlyContinue
Set-Content -Path $fullname -Value "Backup has been completed"
Write-Log -Message "Token File $fullname has been created" -Level "INFO"
return $fullName
}
function SendTokenFile {
param (
[string]$localPathAndFileName,
[string]$remotePathAndFileName
)
Write-Host "Preparing to send file: $fileNameToSendToPi"
Write-Log -Message "In SendTokenFile $fullname has been created" -Level "INFO"
# Create a new instance of the WinSCP session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = '192.168.0.177'
$sessionOptions.PortNumber = 22
$sessionOptions.UserName = "macrium_user"
$sessionOptions.Password = "5GI9jf7LOuvR9yK8"
$sessionOptions.SshHostKeyFingerprint = "Az6IF7qR6dHSH+lkdRJQ7Pb5nR9L5AnGoJ3oEjKyZGw"
# Create a new instance of the WinSCP session
$session = New-Object WinSCP.Session
try {
Write-Host "Connecting to the server"
Write-Log -Message "Connecting to the server" -Level "INFO"
$session.Open($sessionOptions)
Write-Host "Connected successfully"
Write-Log -Message "Connected successfully" -Level "INFO"
Write-Host "Uploading file: $localPathAndFileName to $remotePathAndFileName"
Write-Log -Message "Uploading file: $localPathAndFileName to $remotePathAndFileName" -Level "INFO"
#$remoteDirectory = Split-Path -Path $remotePathAndFileName
#$remoteFilename = Split-Path -Path $remotePathAndFileName -Leaf
$session.PutFiles($localPathAndFileName, $remotePathAndFileName).Check()
Write-Host "File uploaded successfully"
Write-Log -Message "File uploaded successfully" -Level "INFO"
}
catch {
Write-Host "Error: $($_.Exception.Message)"
Write-Log -Message "Error: $($_.Exception.Message)" -Level "INFO"
}
finally {
$session.Dispose()
}
}
function Write-Log {
param (
[string]$Message,
[string]$Level = "INFO",
[string]$LogFilePath = "C:\mytemp\macrium reflect token file process.log"
)
# Get the current date and time
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Create the log message
$logMessage = "$timestamp [$Level] $Message"
# Write the log message to the log file
Add-Content -Path $LogFilePath -Value $logMessage
}
Main
# CreateLocalTokenFile