forked from Seidlm/PowerShell-Backup-Script
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackupScript.ps1
346 lines (279 loc) · 14.2 KB
/
BackupScript.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
########################################################
# Name: BackupScript.ps1
# Creator: Michael Seidl aka Techguy
# CreationDate: 21.01.2014
# LastModified: 31.03.2020
# Version: 1.5
# Doc: http://www.techguy.at/tag/backupscript/
# GitHub: https://github.com/Seidlm/PowerShell-Backup-Script
# PSVersion tested: 3 and 4
#
# PowerShell Self Service Web Portal at www.au2mator.com/PowerShell
#
#
# Description: Copies the Bakupdirs to the Destination
# You can configure more than one Backupdirs, every Dir
# wil be copied to the Destination. A Progress Bar
# is showing the Status of copied MB to the total MB
# Only Change Variables in Variables Section
# Change LoggingLevel to 3 an get more output in Powershell Windows
#
#
########################################################
#
# www.techguy.at
# www.facebook.com/TechguyAT
# www.twitter.com/TechguyAT
#
#
########################################################
#Variables, only Change here
$Destination = "\\SVATHOME002\Backup$\NB BaseIT" #Copy the Files to this Location
$Staging = "C:\Users\seimi\Downloads\Staging"
$ClearStaging = $true # When $true, Staging Dir will be cleared
$Versions = "15" #How many of the last Backups you want to keep
$BackupDirs = "C:\Users\seimi\Documents" #What Folders you want to backup
$ExcludeDirs = #This list of Directories will not be copied
($env:SystemDrive + "\Users\.*\AppData\Local")
#($env:SystemDrive + "\Users\.*\AppData\LocalLow"),
#"C:\Users\seimi\OneDrive - Seidl Michael\0-Temp",
#"C:\Users\seimi\OneDrive - Seidl Michael\0-Temp\Dir2"
$LogfileName = "Log" #Log Name
$LoggingLevel = "3" #LoggingLevel only for Output in Powershell Window, 1=smart, 3=Heavy
$Zip = $true #Zip the Backup Destination
$Use7ZIP = $false #Make sure it is installed
$RemoveBackupDestination = $true #Remove copied files after Zip, only if $Zip is true
$UseStaging = $false #only if you use ZIP, than we copy file to Staging, zip it and copy the ZIP to destination, like Staging, and to save NetworkBandwith
#Send Mail Settings
$SendEmail = $false # = $true if you want to enable send report to e-mail (SMTP send)
$EmailTo = '[email protected]' #[email protected] (for multiple users use "User01 <[email protected]>" ,"User02 <[email protected]>" )
$EmailFrom = '[email protected]' #matthew@domain
$EmailSMTP = 'smtp.domain.com' #smtp server adress, DNS hostname.
#STOP-no changes from here
#STOP-no changes from here
#Settings - do not change anything from here
$ExcludeString = ""
foreach ($Entry in $ExcludeDirs) {
#Exclude the directory itself
$Temp = "^" + $Entry.Replace("\", "\\") + "$"
$ExcludeString += $Temp + "|"
#Exclude the directory's children
$Temp = "^" + $Entry.Replace("\", "\\") + "\\.*"
$ExcludeString += $Temp + "|"
}
$ExcludeString = $ExcludeString.Substring(0, $ExcludeString.Length - 1)
[RegEx]$exclude = $ExcludeString
if ($UseStaging -and $Zip) {
#Logging "INFO" "Use Temp Backup Dir"
$Backupdir = $Staging + "\Backup-" + (Get-Date -format yyyy-MM-dd) + "-" + (Get-Random -Maximum 100000) + "\"
}
else {
#Logging "INFO" "Use orig Backup Dir"
$Backupdir = $Destination + "\Backup-" + (Get-Date -format yyyy-MM-dd) + "-" + (Get-Random -Maximum 100000) + "\"
}
#$BackupdirTemp=$Temp +"\Backup-"+ (Get-Date -format yyyy-MM-dd)+"-"+(Get-Random -Maximum 100000)+"\"
$logPath = $Backupdir
$Items = 0
$Count = 0
$ErrorCount = 0
$StartDate = Get-Date #-format dd.MM.yyyy-HH:mm:ss
#FUNCTION
#Logging
function Write-au2matorLog {
[CmdletBinding()]
param
(
[ValidateSet('DEBUG', 'INFO', 'WARNING', 'ERROR')]
[string]$Type,
[string]$Text
)
# Set logging path
if (!(Test-Path -Path $logPath)) {
try {
$null = New-Item -Path $logPath -ItemType Directory
Write-Verbose ("Path: ""{0}"" was created." -f $logPath)
}
catch {
Write-Verbose ("Path: ""{0}"" couldn't be created." -f $logPath)
}
}
else {
Write-Verbose ("Path: ""{0}"" already exists." -f $logPath)
}
[string]$logFile = '{0}\{1}_{2}.log' -f $logPath, $(Get-Date -Format 'yyyyMMdd'), $LogfileName
$logEntry = '{0}: <{1}> <{2}> {3}' -f $(Get-Date -Format dd.MM.yyyy-HH:mm:ss), $Type, $PID, $Text
try { Add-Content -Path $logFile -Value $logEntry }
catch {
Start-sleep -Milliseconds 50
Add-Content -Path $logFile -Value $logEntry
}
if ($LoggingLevel -eq "3") { Write-Host $Text }
}
#Create Backupdir
Function New-Backupdir {
New-Item -Path $Backupdir -ItemType Directory | Out-Null
Start-sleep -Seconds 5
Write-au2matorLog -Type Info -Text "Create Backupdir $Backupdir"
}
#Delete Backupdir
Function Remove-Backupdir {
$Folder = Get-ChildItem $Destination | where { $_.Attributes -eq "Directory" } | Sort-Object -Property CreationTime -Descending:$false | Select-Object -First 1
Write-au2matorLog -Type Info -Text "Remove Dir: $Folder"
$Folder.FullName | Remove-Item -Recurse -Force
}
#Delete Zip
Function Remove-Zip {
$Zip = Get-ChildItem $Destination | where { $_.Attributes -eq "Archive" -and $_.Extension -eq ".zip" } | Sort-Object -Property CreationTime -Descending:$false | Select-Object -First 1
Write-au2matorLog -Type Info -Text "Remove Zip: $Zip"
$Zip.FullName | Remove-Item -Recurse -Force
}
#Check if Backupdirs and Destination is available
function Check-Dir {
Write-au2matorLog -Type Info -Text "Check if BackupDir and Destination exists"
if (!(Test-Path $BackupDirs)) {
return $false
Write-au2matorLog -Type Error -Text "$BackupDirs does not exist"
}
if (!(Test-Path $Destination)) {
return $false
Write-au2matorLog -Type Error -Text "$Destination does not exist"
}
}
#Save all the Files
Function Make-Backup {
Write-au2matorLog -Type Info -Text "Started the Backup"
$BackupDirFiles = @{ } #Hash of BackupDir & Files
$Files = @()
$SumMB = 0
$SumItems = 0
$SumCount = 0
$colItems = 0
Write-au2matorLog -Type Info -Text "Count all files and create the Top Level Directories"
foreach ($Backup in $BackupDirs) {
# Get recursive list of files for each Backup Dir once and save in $BackupDirFiles to use later.
# Optimize performance by getting included folders first, and then only recursing files for those.
# Use -LiteralPath option to work around known issue with PowerShell FileSystemProvider wildcards.
# See: https://github.com/PowerShell/PowerShell/issues/6733
$Files = Get-ChildItem -LiteralPath $Backup -recurse -Attributes D+!ReparsePoint, D+H+!ReparsePoint -ErrorVariable +errItems -ErrorAction SilentlyContinue |
ForEach-Object -Process { Add-Member -InputObject $_ -NotePropertyName "ParentFullName" -NotePropertyValue ($_.FullName.Substring(0, $_.FullName.LastIndexOf("\" + $_.Name))) -PassThru -ErrorAction SilentlyContinue } |
Where-Object { $_.FullName -notmatch $exclude -and $_.ParentFullName -notmatch $exclude } |
Get-ChildItem -Attributes !D -ErrorVariable +errItems -ErrorAction SilentlyContinue | Where-Object { $_.DirectoryName -notmatch $exclude }
$BackupDirFiles.Add($Backup, $Files)
$colItems = ($Files | Measure-Object -property length -sum)
$Items = 0
Copy-Item -LiteralPath $Backup -Destination $Backupdir -Force -ErrorAction SilentlyContinue | Where-Object { $_.FullName -notmatch $exclude }
$SumMB += $colItems.Sum.ToString()
$SumItems += $colItems.Count
}
$TotalMB = "{0:N2}" -f ($SumMB / 1MB) + " MB of Files"
Write-au2matorLog -Type Info -Text "There are $SumItems Files with $TotalMB to copy"
#Log any errors from above from building the list of files to backup.
[System.Management.Automation.ErrorRecord]$errItem = $null
foreach ($errItem in $errItems) {
Write-au2matorLog -Type ERROR -Text ("Skipping `"" + $errItem.TargetObject + "`" Error: " + $errItem.CategoryInfo)
}
Remove-Variable errItem
Remove-Variable errItems
foreach ($Backup in $BackupDirs) {
$Index = $Backup.LastIndexOf("\")
$SplitBackup = $Backup.substring(0, $Index)
$Files = $BackupDirFiles[$Backup]
foreach ($File in $Files) {
$restpath = $file.fullname.replace($SplitBackup, "")
try {
# Use New-Item to create the destination directory if it doesn't yet exist. Then copy the file.
New-Item -Path (Split-Path -Path $($Backupdir + $restpath) -Parent) -ItemType "directory" -Force -ErrorAction SilentlyContinue | Out-Null
Copy-Item -LiteralPath $file.fullname $($Backupdir + $restpath) -Force -ErrorAction SilentlyContinue | Out-Null
Write-au2matorLog -Type Info -Text $("'" + $File.FullName + "' was copied")
}
catch {
$ErrorCount++
Write-au2matorLog -Type Error -Text $("'" + $File.FullName + "' returned an error and was not copied")
}
$Items += (Get-item -LiteralPath $file.fullname).Length
$status = "Copy file {0} of {1} and copied {3} MB of {4} MB: {2}" -f $count, $SumItems, $file.Name, ("{0:N2}" -f ($Items / 1MB)).ToString(), ("{0:N2}" -f ($SumMB / 1MB)).ToString()
$Index = [array]::IndexOf($BackupDirs, $Backup) + 1
$Text = "Copy data Location {0} of {1}" -f $Index , $BackupDirs.Count
Write-Progress -Activity $Text $status -PercentComplete ($Items / $SumMB * 100)
if ($File.Attributes -ne "Directory") { $count++ }
}
}
$SumCount += $Count
$SumTotalMB = "{0:N2}" -f ($Items / 1MB) + " MB of Files"
Write-au2matorLog -Type Info -Text "----------------------"
Write-au2matorLog -Type Info -Text "Copied $SumCount files with $SumTotalMB"
Write-au2matorLog -Type Info -Text "$ErrorCount Files could not be copied"
# Send e-mail with reports as attachments
if ($SendEmail -eq $true) {
$EmailSubject = "Backup Email $(get-date -format MM.yyyy)"
$EmailBody = "Backup Script $(get-date -format MM.yyyy) (last Month).`nYours sincerely `Matthew - SYSTEM ADMINISTRATOR"
Write-au2matorLog -Type Info -Text "Sending e-mail to $EmailTo from $EmailFrom (SMTPServer = $EmailSMTP) "
### the attachment is $log
Send-MailMessage -To $EmailTo -From $EmailFrom -Subject $EmailSubject -Body $EmailBody -SmtpServer $EmailSMTP -attachment $Log
}
}
#create Backup Dir
New-Backupdir
Write-au2matorLog -Type Info -Text "----------------------"
Write-au2matorLog -Type Info -Text "Start the Script"
#Check if Backupdir needs to be cleaned and create Backupdir
$Count = (Get-ChildItem $Destination | where { $_.Attributes -eq "Directory" }).count
Write-au2matorLog -Type Info -Text "Check if there are more than $Versions Directories in the Backupdir"
if ($count -gt $Versions) {
Write-au2matorLog -Type Info -Text "Found $count Backups"
Remove-Backupdir
}
$CountZip = (Get-ChildItem $Destination | where { $_.Attributes -eq "Archive" -and $_.Extension -eq ".zip" }).count
Write-au2matorLog -Type Info -Text "Check if there are more than $Versions Zip in the Backupdir"
if ($CountZip -gt $Versions) {
Remove-Zip
}
#Check if all Dir are existing and do the Backup
$CheckDir = Check-Dir
if ($CheckDir -eq $false) {
Write-au2matorLog -Type Error -Text "One of the Directories are not available, Script has stopped"
}
else {
Make-Backup
$Enddate = Get-Date #-format dd.MM.yyyy-HH:mm:ss
$span = $EndDate - $StartDate
$Duration = $("Backup duration " + $span.Hours.ToString() + " hours " + $span.Minutes.ToString() + " minutes " + $span.Seconds.ToString() + " seconds")
Write-au2matorLog -Type Info -Text "$Duration"
Write-au2matorLog -Type Info -Text "----------------------"
Write-au2matorLog -Type Info -Text "----------------------"
if ($Zip) {
Write-au2matorLog -Type Info -Text "Compress the Backup Destination"
if ($Use7ZIP) {
Write-au2matorLog -Type Info -Text "Use 7ZIP"
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) { Write-au2matorLog -Type Warning -Text "7Zip not found" }
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
#sz a -t7z "$directory\$zipfile" "$directory\$name"
if ($UseStaging -and $Zip) {
$Zip = $Staging + ("\" + $Backupdir.Replace($Staging, '').Replace('\', '') + ".zip")
sz a -t7z $Zip $Backupdir
Write-au2matorLog -Type Info -Text "Move Zip to Destination"
Move-Item -Path $Zip -Destination $Destination
if ($ClearStaging) {
Write-au2matorLog -Type Info -Text "Clear Staging"
Get-ChildItem -Path $Staging -Recurse -Force | remove-item -Confirm:$false -Recurse -force
}
}
else {
sz a -t7z ($Destination + ("\" + $Backupdir.Replace($Destination, '').Replace('\', '') + ".zip")) $Backupdir
}
}
else {
Write-au2matorLog -Type Info -Text "Use Powershell Compress-Archive"
Compress-Archive -Path $Backupdir -DestinationPath ($Destination + ("\" + $Backupdir.Replace($Destination, '').Replace('\', '') + ".zip")) -CompressionLevel Optimal -Force
}
If ($RemoveBackupDestination) {
Write-au2matorLog -Type Info -Text "$Duration"
#Remove-Item -Path $BackupDir -Force -Recurse
get-childitem -Path $BackupDir -recurse -Force | remove-item -Confirm:$false -Recurse
get-item -Path $BackupDir | remove-item -Confirm:$false -Recurse
}
}
}
Write-Host "Press any key to close ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")