-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathPlexBackup.ps1
4159 lines (3412 loc) · 135 KB
/
PlexBackup.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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#------------------------------[ HELP INFO ]-------------------------------
<#
.SYNOPSIS
Backs up and restores Plex application data files and registry keys on a Windows system.
.DESCRIPTION
The script can run in these modes:
- Backup : A default mode to initiate a new backup.
- Continue : Continues from where a previous backup stopped.
- Restore : Restores Plex app data from a backup.
The script backs up the contents of the 'Plex Media Server' folder (app data folder) with the exception of some top-level, non-essential folders. You can customize the list of folders that do not need to be backed up. By default, the following top-level app data folders are not backed up:
- Diagnostics
- Crash Reports
- Updates
- Logs
The backup process compresses the contents Plex app data folders to the ZIP files (with the exception of folders containing subfolders and files with really long paths). For efficiency reasons, the script first compresses the data in a temporary folder and then copies the compressed (ZIP) files to the backup destination folder. You can compress data to the backup destination folder directly (bypassing the saving to the temp folder step) by setting the value of the $TempZipFileDir variable to null or empty string. Folders holding subfolders and files with very long paths get special treatment: instead of compressing them, before performing the backup, the script moves them to the backup folder as-is, and after the backup, it copies them to their original locations. Alternatively, backup can create a mirror of the essential app data folder via the Robocopy command (to use this option, set the -Robocopy switch).
In addition to backing up Plex app data, the script also backs up the contents of the Plex Windows Registry key.
The backup is created in the specified backup folder under a subfolder which name reflects the script start time. It deletes the old backup folders (you can specify the number of old backup folders to keep).
If the backup process does not complete due to error, you can run backup in the Continue mode (using the '-Mode Continue' command-line switch) and it will resume from where it left off. By default, the script picks up the most recent backup folder, but you can specify the backup folder using the -BackupDirPath command-line switch.
When restoring Plex application data from a backup, the script expects the backup folder structure to be the same as the one it creates when it runs in the backup mode. By default, it use the backup folder with the name reflecting the most recent timestamp, but you can specify an alternative backup folder.
Before creating backup or restoring data from a backup, the script stops all running Plex services and the Plex Media Server process (it restarts them once the operation is completed). You can force the script to not start the Plex Media Server process via the -Shutdown switch.
To override the default script settings, modify the values of script parameters and global variables inline or specify them in a config file.
The script can send an email notification on the operation completion.
The config file must use the JSON format. Not every script variable can be specified in the config file (for the list of overridable variables, see the sample config file). Only non-null values from config file will be used. The default config file is named after the running script with the '.json' extension, such as: PlexBackup.ps1.json. You can specify a custom config file via the -ConfigFile command-line switch. Config file is optional. All config values in the config file are optional. The non-null config file settings override the default and command-line paramateres, e.g. if the command-line -Mode switch is set to 'Backup' and the corresponding element in the config file is set to 'Restore' then the script will run in the Restore mode.
On success, the script will set the value of the $LASTEXITCODE variable to 0; on error, it will be greater than zero.
This script must run as an administrator.
The execution policy must allow running scripts. To check execution policy, run the following command:
Get-ExecutionPolicy
If the execution policy does not allow running scripts, do the following:
(1) Start Windows PowerShell with the "Run as Administrator" option.
(2) Run the following command:
Set-ExecutionPolicy RemoteSigned
This will allow running unsigned scripts that you write on your local computer and signed scripts from Internet.
Alternatively, you may want to run the script as:
start powershell.exe -noprofile -executionpolicy bypass -file .\PlexBackup.ps1 -ConfigFile .\PlexBackup.ps1.json
See also 'Running Scripts' at Microsoft TechNet Library:
https://docs.microsoft.com/en-us/previous-versions//bb613481(v=vs.85)
.PARAMETER Mode
Specifies the mode of operation:
- Backup (default)
- Continue
- Restore
.PARAMETER Backup
Shortcut for '-Mode Backup'.
.PARAMETER Continue
Shortcut for '-Mode Continue'.
.PARAMETER Restore
Shortcut for '-Mode Restore'.
.PARAMETER Type
Specifies the non-default type of backup method:
- 7zip
- Robocopy
By default, the script will use the built-in compression.
.PARAMETER SevenZip
Shortcut for '-Type 7zip'
.PARAMETER Robocopy
Shortcut for '-Type Robocopy'.
.PARAMETER ModuleDir
Optional path to directory holding the modules used by this script. This can be useful if the script runs on the system with no or restricted access to the Internet. By default, the module path will point to the 'Modules' folder in the script's folder.
.PARAMETER ConfigFile
Path to the optional custom config file. The default config file is named after the script with the '.json' extension, such as 'PlexBackup.ps1.json'.
.PARAMETER PlexAppDataDir
Location of the Plex Media Server application data folder.
.PARAMETER BackupRootDir
Path to the root backup folder holding timestamped backup subfolders. If not specified, the script folder will be used.
.PARAMETER BackupDirPath
When running the script in the 'Restore' mode, holds path to the backup folder (by default, the subfolder with the most recent timestamp in the name located in the backup root folder will be used).
.PARAMETER TempDir
Temp folder used to stage the archiving job (use local drive for efficiency). To bypass the staging step, set this parameter to null or empty string.
.PARAMETER WakeUpDir
Optional path to a remote share that may need to be woken up before starting Plex Media Server.
.PARAMETER ArchiverPath
Defines the path to the 7-zip command line tool (7z.exe) which is required when running the script with the '-Type 7zip' or '-SevenZip' switch. Default: $env:ProgramFiles\7-Zip\7z.exe.
.PARAMETER Quiet
Set this switch to suppress log entries sent to a console.
.PARAMETER LogLevel
Specifies the log level of the output:
- None
- Error
- Warning
- Info
- Debug
.PARAMETER Log
When set to true, informational messages will be written to a log file. The default log file will be created in the backup folder and will be named after this script with the '.log' extension, such as 'PlexBackup.ps1.log'.
.PARAMETER LogFile
Use this switch to specify a custom log file location. When this parameter is set to a non-null and non-empty value, the '-Log' switch can be omitted.
.PARAMETER ErrorLog
When set to true, error messages will be written to an error log file. The default error log file will be created in the backup folder and will be named after this script with the '.err.log' extension, such as 'PlexBackup.ps1.err.log'.
.PARAMETER ErrorLogFile
Use this switch to specify a custom error log file location. When this parameter is set to a non-null and non-empty value, the '-ErrorLog' switch can be omitted.
.PARAMETER Keep
Number of old backups to keep:
0 - retain all previously created backups,
1 - latest backup only,
2 - latest and one before it,
3 - latest and two before it,
and so on.
.PARAMETER Retries
The number of retries on failed copy operations (corresponds to the Robocopy /R switch).
.PARAMETER RetryWaitSec
Specifies the wait time between retries in seconds (corresponds to the Robocopy /W switch).
.PARAMETER RawOutput
Set this switch to display raw output from the external commands, such as Robocopy or 7-zip.
.PARAMETER Inactive
When set, allows the script to continue if Plex Media Server is not running.
.PARAMETER NoRestart
Set this switch to not start the Plex Media Server process at the end of the operation (could be handy for restores, so you can double check that all is good before launching Plex media Server).
.PARAMETER NoSingleton
Set this switch to ignore check for multiple script instances running concurrently.
.PARAMETER NoVersion
Forces restore to ignore version mismatch between the current version of Plex Media Server and the version of Plex Media Server active during backup.
.PARAMETER NoLogo
Specify this command-line switch to not print version and copyright info.
.PARAMETER Test
When turned on, the script will not generate backup files or restore Plex app data from the backup files.
.PARAMETER SendMail
Indicates in which case the script must send an email notification about the result of the operation:
- Never (default)
- Always
- OnError (for any operation)
- OnSuccess (for any operation)
- OnBackup (for both the Backup and Continue modes on either error or success)
- OnBackupError
- OnBackupSuccess
- OnRestore (on either error or success)
- OnRestoreError
- OnRestoreSuccess
.PARAMETER SmtpServer
Defines the SMTP server host. If not specified, the notification will not be sent.
.PARAMETER Port
Specifies an alternative port on the SMTP server. Default: 0 (zero, i.e. default port 25 will be used).
.PARAMETER From
Specifies the email address when email notification sender. If this value is not provided, the username from the credentails saved in the credentials file or entered at the credentials prompt will be used. If the From address cannot be determined, the notification will not be sent.
.PARAMETER To
Specifies the email address of the email recipient. If this value is not provided, the addressed defined in the To parameter will be used.
.PARAMETER NoSsl
Tells the script not to use the Secure Sockets Layer (SSL) protocol when connecting to the SMTP server. By default, SSL is used.
.PARAMETER CredentialFile
Path to the file holding username and encrypted password of the account that has permission to send mail via the SMTP server. You can generate the file via the following PowerShell command:
Get-Credential | Export-CliXml -Path "PathToFile.xml"
The default log file will be created in the backup folder and will be named after this script with the '.xml' extension, such as 'PlexBackup.ps1.xml'.
.PARAMETER SaveCredential
When set, the SMTP credentials will be saved in a file (encrypted with user- and machine-specific key) for future use.
.PARAMETER Anonymous
Tells the script to not use credentials when sending email notifications.
.PARAMETER SendLogFile
Indicates in which case the script must send an attachment along with th email notification:
- Never (default)
- Always
- OnError
- OnSuccess
.PARAMETER Logoff
Specify this command-line switch to log off all user accounts (except the running one) before starting Plex Media Server. This may help address issues with remote drive mappings under the wrong credentials.
.PARAMETER Reboot
Reboots the computer after a successful backup operation (ignored on restore).
.PARAMETER ForceReboot
Forces an immediate restart of the computer after a successfull backup operation (ignored on restore).
.PARAMETER Machine
Intends to overcome an infrequent error "87: The parameter is incorrect" returned by the runas command attempting to relaunch Plex Media Server:
- x86
- amd64
Keep in mind that these refer to the architecture of the Plex Media Server executable, not to the computer on which it runs, so for the 32-bit version of the server, use 'x86' and for the 64-bit version, use 'amd64'. Do not use this flag if you do not get error 87.
.NOTES
Version : 2.1.9
Author : Alek Davis
Created on : 2024-04-08
License : MIT License
LicenseLink: https://github.com/alekdavis/PlexBackup/blob/master/LICENSE
Copyright : (c) 2024 Alek Davis
.LINK
https://github.com/alekdavis/PlexBackup
.INPUTS
None.
.OUTPUTS
None.
.EXAMPLE
PlexBackup.ps1
Backs up compressed Plex application data to the default backup location.
.EXAMPLE
PlexBackup.ps1 -Robocopy
Backs up Plex application data to the default backup location using the Robocopy command instead of the file and folder compression.
.EXAMPLE
PlexBackup.ps1 -SevenZip
Backs up Plex application data to the default backup location using the 7-zip command-line tool (7z.exe). 7-zip command-line tool must be installed and the script must know its path.
.EXAMPLE
PlexBackup.ps1 -BackupRootDir "\\MYNAS\Backup\Plex"
Backs up Plex application data to the specified backup location on a network share.
.EXAMPLE
PlexBackup.ps1 -Continue
Continues a previous backup process from where it left off.
.EXAMPLE
PlexBackup.ps1 -Restore
Restores Plex application data from the latest backup in the default folder.
.EXAMPLE
PlexBackup.ps1 -Restore -Robocopy
Restores Plex application data from the latest backup in the default folder created using the Robocopy command.
.EXAMPLE
PlexBackup.ps1 -Mode Restore -BackupDirPath "\\MYNAS\PlexBackup\20190101183015" Restores Plex application data from a backup in the specified remote folder.
.EXAMPLE
PlexBackup.ps1 -SendMail Always -Prompt -Save -SendLogFile OnError -SmtpServer smtp.gmail.com -Port 587
Runs a backup job and sends an email notification over an SSL channel. If the backup operation fails, the log file will be attached to the email message. The sender's and the recipient's email addresses will determined from the username of the credential object. The credential object will be set either from the credential file or, if the file does not exist, via a user prompt (in the latter case, the credential object will be saved in the credential file with password encrypted using a user- and computer-specific key).
.EXAMPLE
Get-Help .\PlexBackup.ps1
View help information.
#>
#------------------------------[ IMPORTANT ]-------------------------------
<#
PLEASE MAKE SURE THAT THE SCRIPT STARTS WITH THE COMMENT HEADER ABOVE AND
THE HEADER IS FOLLOWED BY AT LEAST ONE BLANK LINE; OTHERWISE, GET-HELP AND
GETVERSION COMMANDS WILL NOT WORK.
#>
#------------------------[ RUN-TIME REQUIREMENTS ]-------------------------
#Requires -Version 4.0
#Requires -RunAsAdministrator
#------------------------[ COMMAND-LINE SWITCHES ]-------------------------
# Script command-line arguments (see descriptions in the .PARAMETER comments
# above). These parameters can also be specified in the accompanying
# configuration (.json) file.
[Diagnostics.CodeAnalysis.SuppressMessageAttribute( `
'PSAvoidUsingPlainTextForPassword', 'CredentialFile', `
Justification='No need for SecureString, since it holds path, not secret.')]
[CmdletBinding(DefaultParameterSetName="default")]
param (
[Parameter(ParameterSetName="Mode")]
[Parameter(Mandatory, ParameterSetName="ModeType")]
[Parameter(Mandatory, ParameterSetName="ModeSevenZip")]
[Parameter(Mandatory, ParameterSetName="ModeRobocopy")]
[ValidateSet("", "Backup", "Continue", "Restore")]
[string]
$Mode = "",
[Parameter(ParameterSetName="Backup")]
[Parameter(Mandatory, ParameterSetName="BackupType")]
[Parameter(Mandatory, ParameterSetName="BackupSevenZip")]
[Parameter(Mandatory, ParameterSetName="BackupRobocopy")]
[switch]
$Backup,
[Parameter(ParameterSetName="Continue")]
[Parameter(Mandatory, ParameterSetName="ContinueType")]
[Parameter(Mandatory, ParameterSetName="ContinueSevenZip")]
[Parameter(Mandatory, ParameterSetName="ContinueRobocopy")]
[switch]
$Continue,
[Parameter(ParameterSetName="Restore")]
[Parameter(Mandatory, ParameterSetName="RestoreType")]
[Parameter(Mandatory, ParameterSetName="RestoreSevenZip")]
[Parameter(Mandatory, ParameterSetName="RestoreRobocopy")]
[switch]
$Restore,
[Parameter(ParameterSetName="Type")]
[Parameter(Mandatory, ParameterSetName="ModeType")]
[Parameter(Mandatory, ParameterSetName="BackupType")]
[Parameter(Mandatory, ParameterSetName="ContinueType")]
[Parameter(Mandatory, ParameterSetName="RestoreType")]
[ValidateSet("", "7zip", "Robocopy")]
[string]
$Type = "",
[Parameter(ParameterSetName="SevenZip")]
[Parameter(Mandatory, ParameterSetName="ModeSevenZip")]
[Parameter(Mandatory, ParameterSetName="BackupSevenZip")]
[Parameter(Mandatory, ParameterSetName="ContinueSevenZip")]
[Parameter(Mandatory, ParameterSetName="RestoreSevenZip")]
[switch]
$SevenZip,
[Parameter(ParameterSetName="Robocopy")]
[Parameter(Mandatory, ParameterSetName="ModeRobocopy")]
[Parameter(Mandatory, ParameterSetName="BackupRobocopy")]
[Parameter(Mandatory, ParameterSetName="ContinueRobocopy")]
[Parameter(Mandatory, ParameterSetName="RestoreRobocopy")]
[switch]
$Robocopy,
[string]
$ModuleDir = "$PSScriptRoot\Modules",
[Alias("Config")]
[string]
$ConfigFile,
[string]
$PlexAppDataDir = "$env:LOCALAPPDATA\Plex Media Server",
[string]
$BackupRootDir = $PSScriptRoot,
[Alias("BackupDirPath")]
[string]
$BackupDir = $null,
[Alias("TempZipFileDir")]
[AllowEmptyString()]
[string]
$TempDir = $env:TEMP,
[string]
$WakeUpDir = $null,
[string]
$ArchiverPath = "$env:ProgramFiles\7-Zip\7z.exe",
[Alias("Q")]
[switch]
$Quiet,
[ValidateSet("None", "Error", "Warning", "Info", "Debug")]
[string]
$LogLevel = "Info",
[Alias("L")]
[switch]
$Log,
[string]
$LogFile,
[switch]
$ErrorLog,
[string]
$ErrorLogFile,
[ValidateRange(0,[int]::MaxValue)]
[int]
$Keep = 3,
[ValidateRange(0,[int]::MaxValue)]
[int]
$Retries = 5,
[ValidateRange(0,[int]::MaxValue)]
[int]
$RetryWaitSec = 10,
[switch]
$RawOutput,
[switch]
$Inactive,
[Alias("Shutdown")]
[switch]
$NoRestart,
[switch]
$NoSingleton,
[Alias("Force")]
[Alias("NoVersionCheck")]
[switch]
$NoVersion,
[switch]
$NoLogo,
[switch]
$Test,
[ValidateSet(
"Never", "Always", "OnError", "OnSuccess",
"OnBackup", "OnBackupError", "OnBackupSuccess",
"OnRestore", "OnRestoreError", "OnRestoreSuccess")]
[string]
$SendMail = "Never",
[string]
$SmtpServer,
[ValidateRange(0,[int]::MaxValue)]
[int]
$Port = 0,
[string]
$From = $null,
[string]
$To,
[switch]
$NoSsl,
[Alias("Credential")]
[string]
$CredentialFile = $null,
[switch]
$SaveCredential,
[switch]
$Anonymous,
[ValidateSet("Never", "OnError", "OnSuccess", "Always")]
[string]
$SendLogFile = "Never",
[switch]
$Logoff,
[switch]
$Reboot,
[switch]
$ForceReboot,
[ValidateSet("x86", "amd64")]
[string]
$Machine
)
#---------------[ VARIABLES CONFIGURABLE VIA CONFIG FILE ]-----------------
# The following Plex application folders do not need to be backed up.
$ExcludeDirs = @(
"Diagnostics",
"Crash Reports",
"Updates",
"Logs"
)
# The following file types do not need to be backed up:
# *.bif - thumbnail previews
# Transcode - cache subfolder used for transcoding and syncs (could be huge)
$ExcludeFiles = @(
"*.bif",
"Transcode"
)
# Subfolders that cannot be archived because the path may be too long.
# Long (over 260 characters) paths cause Compress-Archive to fail,
# so before running the archival steps, we will move these folders to
# the backup directory, and copy it back once the archival step completes.
# On restore, we'll copy these folders from the backup directory to the
# Plex app data folder.
$SpecialDirs = @(
"Plug-in Support\Data\com.plexapp.system\DataItems\Deactivated"
)
# Regular expression used to find display names of the Plex Windows service(s).
$PlexServiceName = "^Plex"
# Name of the Plex Media Server executable file.
$PlexServerFileName = "Plex Media Server.exe"
# If Plex Media Server is not running, define path to the executable here.
$PlexServerPath = $null
# 7-zip command-line option for compression.
$ArchiverOptionsCompress =
@(
$null
)
# 7-zip command-line option for decompression.
$ArchiverOptionsExpand =
@(
$null
)
#-------------------------[ MODULE DEPENDENCIES ]--------------------------
# Module to get script version info:
# https://www.powershellgallery.com/packages/ScriptVersion
# Module to initialize script parameters and variables from a config file:
# https://www.powershellgallery.com/packages/ConfigFile
# Module implementing logging to file and console routines:
# https://www.powershellgallery.com/packages/StreamLogging
# Module responsible for making sure only one instance of the script is running:
# https://www.powershellgallery.com/packages/SingleInstance
$MODULE_ScriptVersion = "ScriptVersion"
$MODULE_ConfigFile = "ConfigFile"
$MODULE_StreamLogging = "StreamLogging"
$MODULE_SingleInstance = "SingleInstance"
$MODULES = @(
$MODULE_ScriptVersion,
$MODULE_ConfigFile,
"$MODULE_StreamLogging|1.2.1",
$MODULE_SingleInstance
)
#------------------------------[ CONSTANTS ]-------------------------------
# Mutex name (to enforce single instance).
$MUTEX_NAME = $PSCommandPath.Replace("\", "/")
# Plex registry key path.
$PLEX_REG_KEYS = @(
"HKCU:\Software\Plex, Inc.\Plex Media Server",
"HKU:\.DEFAULT\Software\Plex, Inc.\Plex Media Server"
)
# Default path of the Plex Media Server.exe.
$DEFAULT_PLEX_SERVER_EXE_PATH = "${env:ProgramFiles(x86)}\Plex\Plex Media Server\Plex Media Server.exe"
# File extensions.
$FILE_EXT_ZIP = ".zip"
$FILE_EXT_7ZIP = ".7z"
$FILE_EXT_REG = ".reg"
$FILE_EXT_CRED = ".xml"
# File names.
$VERSION_FILE_NAME = "Version.txt"
# Backup mode types.
$MODE_BACKUP = "Backup"
$MODE_CONTINUE = "Continue"
$MODE_RESTORE = "Restore"
# Backup types.
$TYPE_ROBOCOPY = "Robocopy"
$TYPE_7ZIP = "7zip"
# Backup folder format: YYYYMMDDhhmmss
$REGEX_BACKUPDIRNAMEFORMAT = "^\d{14}$"
# Format of the backup folder name (so it can be easily sortable).
$BACKUP_DIRNAMEFORMAT = "yyyyMMddHHmmss"
# Subfolders in the backup directory.
$SUBDIR_FILES = "1"
$SUBDIR_FOLDERS = "2"
$SUBDIR_REGISTRY = "3"
$SUBDIR_SPECIAL = "4"
# Name of the common backup files.
$BACKUP_FILENAME = "Plex"
# Send mail settings.
$SEND_MAIL_NEVER = "Never"
$SEND_MAIL_ALWAYS = "Always"
$SEND_MAIL_ERROR = "OnError"
$SEND_MAIL_SUCCESS = "OnSuccess"
$SEND_MAIL_BACKUP = "OnBackup"
$SEND_MAIL_RESTORE = "OnRestore"
$SEND_LOGFILE_NEVER = "Never"
$SEND_LOGFILE_ALWAYS = "Always"
$SEND_LOGFILE_ERROR = "OnError"
$SEND_LOGFILE_SUCCESS = "OnSuccess"
# Set variables for email notification.
$SUBJECT_ERROR = "Plex backup failed :-("
$SUBJECT_SUCCESS = "Plex backup completed :-)"
#------------------------------[ EXIT CODES]-------------------------------
$EXITCODE_SUCCESS = 0 # success
$EXITCODE_ERROR = 1 # error
#----------------------[ NON-CONFIGURABLE VARIABLES ]----------------------
# File extensions.
$ZipFileExt = $FILE_EXT_ZIP
$RegFileExt = $FILE_EXT_REG
# Files and folders.
[string]$BackupDirName = $null
[string]$VersionFilePath = $null
# Version info.
[string]$PlexVersion = $null
[string]$BackupVersion = $null
# Save time for logging purposes.
[DateTime]$StartTime = Get-Date
[DateTime]$EndTime = $StartTime
[string] $Duration = $null
# Mail credentials object.
[PSCredential]$Credential = $null
# Error message set in case of error.
[string]$ErrorResult = $null
# Backup stats.
[string]$ObjectCount = "UNKNOWN"
[string]$BackupSize = "UNKNOWN"
# The default exit code indicates error (we'll set it to success at the end).
$ExitCode = $EXITCODE_ERROR
#--------------------------[ STANDARD FUNCTIONS ]--------------------------
#--------------------------------------------------------------------------
# SetModulePath
# Adds custom folders to the module path.
function SetModulePath {
[CmdletBinding()]
param(
)
WriteDebug "Entered SetModulePath."
if ($Script:ModuleDir) {
if ($env:PSModulePath -notmatch ";$") {
$env:PSModulePath += ";"
}
$paths = $Script:ModuleDir -split ";"
foreach ($path in $paths){
$path = $path.Trim();
if (-not ($env:PSModulePath.ToLower().
Contains(";$path;".ToLower()))) {
$env:PSModulePath += "$path;"
}
}
}
WriteDebug "Exiting SetModulePath."
}
#--------------------------------------------------------------------------
# GetModuleVersion
# Returns version string for the specified module using format:
# major.minor.build.
function GetModuleVersion {
[CmdletBinding()]
param(
[PSModuleInfo]
$moduleInfo
)
$major = $moduleInfo.Version.Major
$minor = $moduleInfo.Version.Minor
$build = $moduleInfo.Version.Build
return "$major.$minor.$build"
}
#--------------------------------------------------------------------------
# GetVersionParts
# Converts version string into three parts: major, minor, and build.
function GetVersionParts {
[CmdletBinding()]
param(
[string]
$version
)
$versionParts = $version.Split(".")
$major = $versionParts[0]
$minor = 0
$build = 0
if ($versionParts.Count -gt 1) {
$minor = $versionParts[1]
}
if ($versionParts.Count -gt 2) {
$build = $versionParts[2]
}
return $major, $minor, $build
}
#--------------------------------------------------------------------------
# CompareVersions
# Compares two major, minor, and build parts of two version strings and
# returns 0 is they are the same, -1 if source version is older, or 1
# if source version is newer than target version.
function CompareVersions {
[CmdletBinding()]
param(
[string]
$sourceVersion,
[string]
$targetVersion
)
if ($sourceVersion -eq $targetVersion) {
return 0
}
$sourceMajor, $sourceMinor, $sourceBuild = GetVersionParts $sourceVersion
$targetMajor, $targetMinor, $targetBuild = GetVersionParts $targetVersion
$source = @($sourceMajor, $sourceMinor, $sourceBuild)
$target = @($targetMajor, $targetMinor, $targetBuild)
for ($i = 0; $i -lt $source.Count; $i++) {
$diff = $source[$i] - $target[$i]
if ($diff -ne 0) {
if ($diff -lt 0) {
return -1
}
return 1
}
}
return 0
}
#--------------------------------------------------------------------------
# IsSupportedVersion
# Checks whether the specified version is within the min-max range.
function IsSupportedVersion {
[CmdletBinding()]
param(
[string]
$version,
[string]
$minVersion,
[string]
$maxVersion
)
if (!($minVersion) -and (!($maxVersion))) {
return $true
}
if (($version -and $minVersion -and $maxVersion) -and
($minVersion -eq $maxVersion) -and
($version -eq $minVersion)) {
return 0
}
if ($minVersion) {
if ((CompareVersions $version $minVersion) -lt 0) {
return $false
}
}
if ($maxVersion) {
if ((CompareVersions $version $maxVersion) -gt 0) {
return $false
}
}
return $true
}
#--------------------------------------------------------------------------
# LoadModules
# Installs (if needed) and loads the specified PowerShell modules.
function LoadModules {
[CmdletBinding()]
param(
[string[]]
$modules
)
WriteDebug "Entered LoadModules."
# Make sure we got the modules.
if (!($modules) -or ($modules.Count -eq 0)) {
return
}
$module = ""
$cmdArgs = @{}
try {
foreach ($module in $modules) {
Write-Verbose "Processing module '$module'."
$moduleInfo = $module.Split("|:")
$moduleName = $moduleInfo[0]
$moduleVersion = ""
$moduleMinVersion = ""
$moduleMaxVersion = ""
$cmdArgs.Clear()
if ($moduleInfo.Count -gt 1) {
$moduleMinVersion = $moduleInfo[1]
if ($moduleMinVersion) {
$cmdArgs["MinimumVersion"] = $moduleMinVersion
}
}
if ($moduleInfo.Count -gt 2) {
$moduleMaxVersion = $moduleInfo[2]
if ($moduleMaxVersion) {
$cmdArgs["MaximumVersion"] = $moduleMaxVersion
}
}
Write-Verbose "Required module name: '$moduleName'."
if ($moduleMinVersion) {
Write-Verbose "Required module min version: '$moduleMinVersion'."
}
if ($moduleMaxVersion) {
Write-Verbose "Required module max version: '$moduleMaxVersion'."
}
# Check if module is loaded into the process.
$loadedModules = Get-Module -Name $moduleName
$isLoaded = $false
$isInstalled = $false
if ($loadedModules) {
Write-Verbose "Module '$moduleName' is loaded."
# If version check is required, compare versions.
if ($moduleMinVersion -or $moduleMaxVersion) {
foreach ($loadedModule in $loadedModules) {
$moduleVersion = GetModuleVersion $loadedModule
Write-Verbose "Checking if loaded module '$moduleName' version '$moduleVersion' is supported."
if (IsSupportedVersion $moduleVersion $moduleMinVersion $moduleMaxVersion) {
Write-Verbose "Loaded module '$moduleName' version '$moduleVersion' is supported."
$isLoaded = $true
$isInstalled = $true
break
} else {
Write-Verbose "Loaded module '$moduleName' version '$moduleVersion' is not supported."
}
}
} else {
$isLoaded = $true
$isInstalled = $true
}
}
# If module is not loaded or version is wrong.
if (!$isLoaded) {
Write-Verbose "Required module '$moduleName' is not loaded."
# Check if module is locally available.
$installedModules = Get-Module -ListAvailable -Name $moduleName
$isInstalled = $false
# If module is found, validate the version.
if ($installedModules) {
foreach ($installedModule in $installedModules) {
$installedModuleVersion = GetModuleVersion $installedModule
Write-Verbose "Found installed '$moduleName' module version '$installedModuleVersion'."
if (IsSupportedVersion $installedModuleVersion $moduleMinVersion $moduleMaxVersion) {
Write-Verbose "Module '$moduleName' version '$moduleVersion' is supported."
$isInstalled = $true
break
}
Write-Verbose "Module '$moduleName' version '$moduleVersion' is not supported."
Write-Verbose "Supported module '$moduleName' versions are: '$moduleMinVersion'-'$moduleMaxVersion'."
}
}
}
if (!$isInstalled) {
# Download module if needed.
Write-Verbose "Installing module '$moduleName'."
Install-Module -Name $moduleName @cmdArgs -Force -Scope CurrentUser -ErrorAction Stop
}
# Import module into the process.
Write-Verbose "Importing module '$moduleName'."
Import-Module $moduleName -ErrorAction Stop -Force @cmdArgs
Write-Verbose "Imported module '$moduleName'."
}
}
catch {
$errMsg = "Cannot load module '$module'."
throw (New-Object System.Exception($errMsg, $_.Exception))
}
finally {
WriteDebug "Exiting LoadModules."
}
}
#--------------------------------------------------------------------------
# GetScriptVersion
# Returns script version info.
function GetScriptVersion {
[CmdletBinding()]
param (
)
WriteDebug "Entered GetScriptVersion."
$versionInfo = Get-ScriptVersion
$scriptName = (Get-Item $PSCommandPath).Basename