-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup_script_en.ps1
More file actions
212 lines (171 loc) · 8.8 KB
/
backup_script_en.ps1
File metadata and controls
212 lines (171 loc) · 8.8 KB
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
###############################################################################
############################ BackUp Script by WeoM ############################
###############################################################################
$version = "2.0"
#!WARNING! The script is simple, so any errors you make when editing configs are not checked.
################################### Configs ###################################
$target = "D:\BackupFolderName\" # the folder where the backups will be saved
$date = Get-Date -Format "yyyy_MM_dd" # current date in format 2024_01_01
$filename = "backup_$date.7z" # name of the resulting file
$pswd = "" # optionally you can add a password to the archive, to do this you need to enter the desired password between ""
[bool]$logEnabled = $false # to activate logging to file change $false to $true
[bool]$force = $false # (silent mode) to create a backup without confirmation change $false to $true
$waitTimeInSeconds = 5 # time in seconds before closing the console window
##################################### Log #####################################
if($logEnabled){ Start-Transcript -Path "$target\logs\backup_$date.log" -Force }
###############################################################################
$path = $PSScriptRoot # get the path to folder where the executable script is located: source.txt exclude.txt 7z.exe 7z.dll
$7z = Join-Path -Path $path -ChildPath "7z.exe"
$sourceList = Join-Path -Path $path -ChildPath "source.txt" # in source.txt add paths to folders and files for backup
$excludeList = Join-Path -Path $path -ChildPath "exclude.txt" # exclusions are added to exclude.txt
$scriptName = "BackUp Script $version by WeoM"
#!WARNING! in source.txt and exclude.txt files it is necessary to use absolute paths because of the -spf2 key
################################## functions ##################################
#Load lib WinForms
Add-Type -AssemblyName System.Windows.Forms
function Get-Timestamp {
return (Get-Date).ToString("dd.MM.yyyy HH:mm:ss")
}
function Get-MsgBox {
param ( [Parameter(Mandatory, Position=0)] [string]$ErrorMessage )
Write-Host $ErrorMessage -ForegroundColor Red
[System.Windows.Forms.MessageBox]::Show("$ErrorMessage", "Error in `"$scriptName`"", [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Error)
}
function Get-Broken7zList {
<#
.SYNOPSIS
Reads a text file line by line, skips empty lines and #-comments, then checks each line for 7-Zip compatibility with -spf2 switch.
.DESCRIPTION
Validation rules:
• Path must be absolute (e.g., C:\... or \\server\share).
• Quotes around path are allowed.
• "/" is auto-converted to "\".
• Path must not contain invalid Windows characters.
• File or directory must exist.
• Duplicates are errors.
• Invalid lines return as array with error reasons.
.PARAMETER Path
Path to file to read (e.g., "source.txt").
.PARAMETER ThrowOnError
If specified, the function will throw an exception if there are any invalid strings.
.EXAMPLE
$badLines = Get-Broken7zList 'C:\source.txt'
if ($badLines.Count) {
Write-Host "Found invalid lines:`n$($badLines -join "`n")" -ForegroundColor Red
} else {
Write-Host 'All paths are valid!' -ForegroundColor Green
}
#>
[CmdletBinding()]
param(
[Parameter(Mandatory, Position=0)] [string]$Path,
[switch]$ThrowOnError
)
if (-not (Test-Path -LiteralPath $Path)) {
throw "File '$Path' not found."
}
$broken = @() # Array for invalid lines
$seen = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase) # HashSet for duplicates (case-insensitive)
$badChars = [System.IO.Path]::GetInvalidPathChars() # Invalid path characters
$validCount = 0 # Counter for valid lines
Get-Content -LiteralPath $Path | ForEach-Object {
$raw = $_
$line = $raw.Trim()
# Skip empty lines and comments
if (-not $line -or $line.StartsWith('#')) { return }
# Remove surrounding quotes (for paths with spaces in 7-Zip)
if ($line.StartsWith('"') -and $line.EndsWith('"')) {
$line = $line.Substring(1, $line.Length-2)
}
# Replace '/' with '\' for Test-Path
$line = $line -replace '/', '\'
if ($line.IndexOfAny($badChars) -ge 0) {
$broken += "$raw <-! contains invalid characters"; return
}
if ($line -notmatch '^[a-zA-Z]:\\|^\\\\') {
$broken += "$raw <-! not absolute path like X:\... or \\server\share"; return
}
if (-not (Test-Path -LiteralPath $line)) {
$broken += "$raw <-! object does not exist"; return
}
if (-not $seen.Add($line.ToLower())) {
$broken += "$raw <-! duplicate: appears multiple times"; return
}
$validCount++
}
if ($broken.Count -and $ThrowOnError) {
throw "$(Get-Timestamp) The file `"source.txt`" contains invalid lines:`n$($broken -join "`n")"
}
if ($validCount -eq 0) {
throw "File '$Path' contains no valid lines."
}
return ,$broken # Comma ensures array return
}
function Start-BackUp {
$run = $force -or (
[System.Windows.Forms.MessageBox]::Show(
"Need to make a backup. Click 'Ok' when you are ready.",
$scriptName,
[System.Windows.Forms.MessageBoxButtons]::OKCancel,
[System.Windows.Forms.MessageBoxIcon]::Information
) -eq [System.Windows.Forms.DialogResult]::OK
)
if($run){
# Checking for the presence of necessary files
$files = @($7z, $sourceList, $excludeList, (Join-Path -Path $path -ChildPath "7z.dll"))
$missing = $files | Where-Object { -not (Test-Path $_) }
if ($missing) {
Get-MsgBox "$(Get-Timestamp) Error! File(s) not found: $($missing -join ', ')."
exit
}
# Checking source.txt
try{
Get-Broken7zList $sourceList -ThrowOnError
} catch {
Get-MsgBox $_
exit
}
$check = $true
$counter = 0
while($check -and $counter -le 4) {
# verification is necessary because of the -mhe key, otherwise the archive will be without a password but with encrypted headers.
if(-not $pswd) {
Write-Host "`n$(Get-Timestamp) Create a backup without a password" -ForegroundColor Magenta
& $7z a -t7z (Join-Path -Path $target -ChildPath $filename) -bt -mx5 -ssw -snh -snl -ssp -spf2 @$sourceList -xr@"$excludeList" -scrcSHA256
} else {
Write-Host "`n$(Get-Timestamp) Create a backup with a password" -ForegroundColor DarkGreen
& $7z a -t7z (Join-Path -Path $target -ChildPath $filename) -bt -mx5 -ssw -snh -snl -ssp -spf2 -p"$pswd" -mhe @$sourceList -xr@"$excludeList" -scrcSHA256
}
# check archive and data integrity
Write-Host "`nCheck archive and data integrity. Wait..." -ForegroundColor Blue
$result = & $7z t (Join-Path -Path $target -ChildPath $filename) -p"$pswd"
if ($result -like "*Everything is Ok*") {
foreach ($line in $result) {
Write-Host $line -ForegroundColor DarkYellow
}
Write-Host "`n$(Get-Timestamp) backup successfully created! `nFile name: $filename `nPath: $target " -ForegroundColor Green
Write-Host "This window will close in $waitTimeInSeconds seconds..."
Start-Sleep -Seconds $waitTimeInSeconds
$check = $false
} else {
Write-Host "`n$(Get-Timestamp) ERROR:" -ForegroundColor Red
foreach ($line in $result) {
Write-Host $line -ForegroundColor Red
}
}
$counter += 1
# if the archive could not be created in 5 attempts, the cycle ends
if ($counter -gt 4) {
Get-MsgBox "$(Get-Timestamp) Failed to create archive after $counter attempts. Operation cancelled."
$check = $false
}
}
} else {
Write-Host "`n$(Get-Timestamp)Backup creation cancelled." -ForegroundColor Red
Write-Host "This window will close in $waitTimeInSeconds seconds..."
Start-Sleep -Seconds $waitTimeInSeconds
}
}
##################################### Run #####################################
Start-BackUp
if($logEnabled){ Stop-Transcript }