├── 7zBackup-vars.ps1 ├── 7zBackup.ps1 ├── 7zBackup.selection.sample.txt ├── LICENSE └── README.md /7zBackup-vars.ps1: -------------------------------------------------------------------------------- 1 | # ==================================================================== 2 | # This is the 7zBackup Default Vars Script File 3 | # ==================================================================== 4 | # VARIABLES - You can hardcode values here if you do not want to 5 | # to pass them by command line. 6 | # -------------------------------------------------------------------- 7 | # Variable : BkType 8 | # Argument Name : --type 9 | # Description : Type of backup to perform. 10 | # Values : full | diff | incr | copy 11 | # Comments 12 | # ------------------------------------------------------------------- 13 | # full : This option performs the archiving of all files in the 14 | # selection paths regardless the state of their archive attribute. 15 | # At successfull archiving operation all archive attributes 16 | # for all archived files are lowered. 17 | # diff : This option is generally used to perform the archiving of 18 | # files in the selection paths that have changed after a previous 19 | # full backup or any backup with option to lower Archive bit 20 | # At successfull completion of archiving operation no changes 21 | # are set on Archive bit 22 | # incr : This option is generally used to perform the archiving of 23 | # files in the selection paths that have changed after a previous 24 | # full backup or any backup with option to lower Archive bit 25 | # At successfull completion of archiving operation all files 26 | # archived have their Archive bit lowered. 27 | # copy : Like FULL backup but leaves archive attribute unchanged 28 | # ------------------------------------------------------------------- 29 | # Uncomment the following Set-Variable statement and set proper 30 | # "" if you want to set the value for the 7zBackup script. 31 | # ------------------------------------------------------------------- 32 | # Set-Variable -Name BkType -Value "" -Scope 1 33 | 34 | # -------------------------------------------------------------------- 35 | # Variable : BkWorkDrive 36 | # Argument Name : --workdrive 37 | # Description : Drive unit to use for making root junction points 38 | # Values : Any valid drive letter 39 | # Comments 40 | # ------------------------------------------------------------------- 41 | # This value holds the drive letter to use for the creation of the root 42 | # junction directory. Default setting is "auto" 43 | # which means the script will try to use the drive letter associated 44 | # to the %TEMP% variable 45 | # Of course, you can change this value using proper command line argument 46 | # ------------------------------------------------------------------- 47 | # Uncomment the following Set-Variable statement and set proper 48 | # "" if you want to set the value for the 7zBackup script. 49 | # ------------------------------------------------------------------- 50 | # Set-Variable -Name BkWorkDrive -Value "" -Scope 1 51 | 52 | # -------------------------------------------------------------------- 53 | # Variable : BkSelection 54 | # Argument Name : --selection 55 | # Description : Full path to the file holding selection directives 56 | # Values : 57 | # Comments 58 | # ------------------------------------------------------------------- 59 | # Generally speaking you should not hardcode this value as you will 60 | # likely pass different selection file names using command line. 61 | # ------------------------------------------------------------------- 62 | # Uncomment the following Set-Variable statement and set proper 63 | # "" if you want to set the value for the 7zBackup script. 64 | # ------------------------------------------------------------------- 65 | # Set-Variable -Name BkSelection -Value "" -Scope 1 66 | 67 | # -------------------------------------------------------------------- 68 | # Variable : BkDestPath 69 | # Argument Name : --destpath 70 | # Description : Full path to directory 71 | # Values : 72 | # Comments 73 | # ------------------------------------------------------------------- 74 | # This is the target folder that will contain the backup archive. Consider this path 75 | # as a sort of library that will contain all of your backups. The real archive name 76 | # will be generated automatically. Can be a UNC path 77 | # ------------------------------------------------------------------- 78 | # Uncomment the following Set-Variable statement and set proper 79 | # "" if you want to set the value for the 7zBackup script. 80 | # ------------------------------------------------------------------- 81 | # Set-Variable -Name BkDestPath -Value "" -Scope 1 82 | 83 | # -------------------------------------------------------------------- 84 | # Variable : BkArchivePrefix 85 | # Argument Name : --prefix 86 | # Description : Prefix to assign to generated archive 87 | # Values : 88 | # Comments 89 | # ------------------------------------------------------------------- 90 | # This variable contains the prefix to use in archive name generation. 91 | # By default this is equal to the COMPUTERNAME environment variable but 92 | # you can choose whichever value you want with no spaces and no quotes. 93 | # The suffix can help you mantain groups of backups and to handle 94 | # retain/rotation policy, as described later. 95 | # Archive name creation template is the following: 96 | # $BkArchivePrefix-$BkType-YYYYMMDD-HH-mm.$BkArchiveType 97 | # ------------------------------------------------------------------- 98 | # Uncomment the following Set-Variable statement and set proper 99 | # "" if you want to set the value for the 7zBackup script. 100 | # ------------------------------------------------------------------- 101 | Set-Variable -Name BkArchivePrefix -Value ($Env:Computername) -Scope 1 102 | 103 | # -------------------------------------------------------------------- 104 | # Variable : BkArchiveType 105 | # Argument Name : --archivetype 106 | # Description : Type of archive to create 107 | # Values : 7z | zip | tar 108 | # Comments 109 | # ------------------------------------------------------------------- 110 | # This variable contains the type of archive you want to create. 111 | # Value can be any of the supported values by 7zip for the -t switch 112 | # except for bzip2 (which is not an archiver) 113 | # 114 | # 7z : default format with better compression 115 | # zip : very compatible with other programs 116 | # tar : Unix and linux compatible but only archiving (no compression) 117 | # 118 | # Archive name creation template is the following: 119 | # $BkArchivePrefix-$BkType-YYYYMMDD-HHmmss.$BkArchiveType 120 | # ------------------------------------------------------------------- 121 | # Uncomment the following Set-Variable statement and set proper 122 | # "" if you want to set the value for the 7zBackup script. 123 | # ------------------------------------------------------------------- 124 | Set-Variable -Name BkArchiveType -Value "7z" -Scope 1 125 | 126 | # -------------------------------------------------------------------- 127 | # Variable : BkArchivePassword 128 | # Argument Name : --password 129 | # Description : Any valid password 130 | # Values : 131 | # Comments 132 | # ------------------------------------------------------------------- 133 | # Set this if you want to password protect your archive 134 | # ------------------------------------------------------------------- 135 | # Uncomment the following Set-Variable statement and set proper 136 | # "" if you want to set the value for the 7zBackup script. 137 | # Please read 7-zip help info for useful informations about password 138 | # complexity 139 | # ------------------------------------------------------------------- 140 | # Set-Variable -Name BkArchivePassword -Value "" -Scope 1 141 | 142 | # -------------------------------------------------------------------- 143 | # Variable : BkArchiveCompression 144 | # Argument Name : --compression 145 | # Description : Any valid value among 0 1 3 5 7 9 146 | # Values : 147 | # Comments 148 | # ------------------------------------------------------------------- 149 | # Set this to calibrate speed vs space reduction 150 | # ------------------------------------------------------------------- 151 | # Uncomment the following Set-Variable statement and set proper 152 | # "" if you want to set the value for the 7zBackup script. 153 | # Please read 7-zip help info for useful informations about password 154 | # complexity 155 | # ------------------------------------------------------------------- 156 | # Set-Variable -Name BkArchiveCompression -Value "< 0 | 1 | 3 | 5 | 7 | 9>" -Scope 1 157 | 158 | # -------------------------------------------------------------------- 159 | # Variable : BkArchiveThreads 160 | # Argument Name : --threads 161 | # Description : An integer number greater than 0 162 | # Values : 163 | # Comments 164 | # ------------------------------------------------------------------- 165 | # This variable sets the number of threads 7-zip should be allowed 166 | # to use. By default 7-zip uses one thread for each available core 167 | # therefore eating up most of computational resources. 168 | # You can limit this behavior by limiting the number of threads 169 | # to be uses therefore keeping your computer responsive. 170 | # Please note that the number of threads can not exceed the number 171 | # of installed cores. 172 | # ------------------------------------------------------------------- 173 | # Uncomment the following Set-Variable statement and set proper 174 | # "" if you want to set the value for the 7zBackup script. 175 | # ------------------------------------------------------------------- 176 | # Set-Variable -Name BkArchiveThreads -Value ([int]4) -Scope 1 177 | # 178 | # - or do a calc, say, to use only 50% of cores - 179 | # 180 | # Set-Variable -Name "tmpNumCores" -Value([int]0) -Scope Local 181 | # Get-WmiObject -class win32_processor | ForEach-Object { 182 | # If($_.NumberOfLogicalProcessors) { 183 | # $tmpNumCores += [int]$_.NumberOfLogicalProcessors 184 | # } 185 | # ElseIf($_.NumberOfCores) { 186 | # $tmpNumCores += [int]$_.NumberOfCores 187 | # } 188 | # Else { 189 | # $tmpNumCores ++ 190 | # } 191 | # } 192 | # Set-Variable -Name BkArchiveThreads -Value ([int]($tmpNumCores * .5)) -Scope 1 193 | # Remove-Variable -Name "tmpNumCores" 194 | 195 | # -------------------------------------------------------------------- 196 | # Variable : BkArchiveSolid 197 | # Argument Name : --solid 198 | # Description : Any boolean value 199 | # Values : Default $True 200 | # Comments 201 | # ------------------------------------------------------------------- 202 | # This variable sets wether or not an archive should endorse solid mode 203 | # To understand what is solid mode please refer to 7-zip documentation 204 | # ------------------------------------------------------------------- 205 | # Uncomment the following Set-Variable statement and set proper 206 | # "" if you want to set the value for the 7zBackup script. 207 | # ------------------------------------------------------------------- 208 | # Set-Variable -Name BkArchiveSolid -Value $True -Scope 1 209 | # Set-Variable -Name BkArchiveSolid -Value $False -Scope 1 210 | # 211 | 212 | # -------------------------------------------------------------------- 213 | # Variable : BkRotate 214 | # Argument Name : --rotate 215 | # Description : An integer number greater than 0 216 | # Values : 217 | # Comments 218 | # ------------------------------------------------------------------- 219 | # This variable holds the number of historycal archive backups you 220 | # want to keep on target media. An zero value means no rotation 221 | # will be performed after succesful archiving and YOU will be in charge 222 | # to delete old backups. Pay attention or your target media 223 | # will run out of free space soon. 224 | # For example: if you set this value to 3 then it means the 3 newest 225 | # backups of the current type are kept on target media. 226 | # For a "classic" 3 week incremental scheme we suggest to : 227 | # $BkRotate=3 for full backups (launched once a week) 228 | # $BkRotate=21 for incr backups (launched once per day) 229 | # ------------------------------------------------------------------- 230 | # Uncomment the following Set-Variable statement and set proper 231 | # "" if you want to set the value for the 7zBackup script. 232 | # ------------------------------------------------------------------- 233 | # Set-Variable -Name BkRotate -Value ([int]3) -Scope 1 234 | 235 | # -------------------------------------------------------------------- 236 | # Variable : BkKeepEmptyDirs 237 | # Argument Name : --emptydirs 238 | # Description : Boolean 239 | # Values : 240 | # Comments 241 | # ------------------------------------------------------------------- 242 | # This variable sets weather or not archive empty directories 243 | # If not defined the script assumes a value of $False (default). 244 | # 245 | # Empty dirs are not really archived. The script drops a dummy file 246 | # into empty dirs to have it archived. After archiving dummy file 247 | # is immediately removed. 248 | # 249 | # ------------------------------------------------------------------- 250 | # Uncomment the following Set-Variable statement and set proper 251 | # "" if you want to set the value for the 7zBackup script. 252 | # ------------------------------------------------------------------- 253 | # Set-Variable -Name BkKeepEmptyDirs -Value $True -Scope 1 254 | 255 | # -------------------------------------------------------------------- 256 | # Variable : BkMaxDepth 257 | # Argument Name : --maxdepth 258 | # Description : An integer number 259 | # Values : 260 | # Comments 261 | # ------------------------------------------------------------------- 262 | # This variable holds the maximum level to be reached in directory 263 | # recursion while scanning for files to backup. 264 | # If not defined the script assumes no limit 265 | # 266 | # The value is zero-based which means a value of zero whil stop the 267 | # the scanning at the first level. A value of 1 will allow 1 recursion 268 | # level therefore scanning the firs level of subfolders and so on 269 | # 270 | # ------------------------------------------------------------------- 271 | # Uncomment the following Set-Variable statement and set proper 272 | # "" if you want to set the value for the 7zBackup script. 273 | # ------------------------------------------------------------------- 274 | # Set-Variable -Name BkMaxDepth -Value ([int]0) -Scope 1 275 | 276 | # -------------------------------------------------------------------- 277 | # Variable : BkLogFile 278 | # Argument Name : --logfile 279 | # Description : Full path you want to assign to log file 280 | # Values : 281 | # Comments 282 | # ------------------------------------------------------------------- 283 | # This variable holds the name of the file where to log operations 284 | # By default it's stored in %temp% directory within a file named 285 | # as the script plus ".log" extension. 286 | # ------------------------------------------------------------------- 287 | # Uncomment the following Set-Variable statement and set proper 288 | # "" if you want to set the value for the 7zBackup script. 289 | # ------------------------------------------------------------------- 290 | # Set-Variable -Name BkLogFile -Value "" -Scope 1 291 | 292 | # -------------------------------------------------------------------- 293 | # Variable : Bk7ZipBin 294 | # Argument Name : --7zipbin 295 | # Description : Full path to 7z.exe 296 | # Values : 297 | # Comments 298 | # ------------------------------------------------------------------- 299 | # 7-zip executable path. 300 | # If you have installed 7zip using standard path, then you do not need to 301 | # change this. 302 | # ------------------------------------------------------------------- 303 | # Uncomment the following Set-Variable statement and set proper 304 | # "" if you want to set the value for the 7zBackup script. 305 | # ------------------------------------------------------------------- 306 | # Set-Variable -Name Bk7ZipBin -Value (Join-Path $Env:ProgramFiles "\7-zip\7z.exe") -Scope 1 307 | 308 | # -------------------------------------------------------------------- 309 | # Variable : BkJunctionBin 310 | # Argument Name : --jbin 311 | # Description : Full path to Junction .exe 312 | # Values : 313 | # Comments 314 | # ------------------------------------------------------------------- 315 | # Find where Junction.exe is and set it here. If Junction.exe is in 316 | # a directory within the PATH variable you can simply indicate 317 | # junction.exe 318 | # 319 | # PLEASE NOTE 320 | # If you're running the script on Vista / 7 / 2008 this variable 321 | # and it's value is completely ignored. Instead of junctions 322 | # Symbolic Links are used (MKLINK). 323 | # ------------------------------------------------------------------- 324 | # Uncomment the following Set-Variable statement and set proper 325 | # "" if you want to set the value for the 7zBackup script. 326 | # ------------------------------------------------------------------- 327 | Set-Variable -Name BkJunctionBin -Value (Join-Path $Env:ProgramFiles "\SysInternalsSuite\Junction.exe") -Scope 1 328 | 329 | # -------------------------------------------------------------------- 330 | # Variable : BkNotifyLog 331 | # Argument Name : --notify or --notifyto 332 | # Description : Holds the email address(es) to send the report 333 | # of operations to. 334 | # Comments 335 | # ------------------------------------------------------------------- 336 | # Use this argument to set a single email address, or a list of email 337 | # addresses, which will receive the detailed report of operations. 338 | # If you mean to address the report to a single email address then 339 | # you will want to set the variable as a normal string. 340 | # If you mean to have multiple addresses to send the report to, then 341 | # you will have to set the variable as an array. 342 | # 343 | # PLEASE NOTE 344 | # Each email address undergoes a check to verify it is properly 345 | # formatted. 346 | # ------------------------------------------------------------------- 347 | # Uncomment the following Set-Variable statement and set proper 348 | # "" if you want to set the value for the 7zBackup script. 349 | # ------------------------------------------------------------------- 350 | # Set-Variable -Name BkNotifyLog -Value "someemail@somedomain.com" -Scope 1 351 | # - or - 352 | # Set-Variable -Name BkNotifyLog -Value @("someemail@somedomain.com", "someotheremail@somedomain.com") -Scope 1 353 | 354 | # -------------------------------------------------------------------- 355 | # Variable : BkNotifyLogCc 356 | # Argument Name : --notifyCc 357 | # Description : Holds the email address(es) to send the report 358 | # of operations in Cc. 359 | # Comments 360 | # ------------------------------------------------------------------- 361 | # Use this argument to set a single email address, or a list of email 362 | # addresses, which will receive the detailed report of operations. 363 | # If you mean to address the report to a single email address then 364 | # you will want to set the variable as a normal string. 365 | # If you mean to have multiple addresses to send the report to, then 366 | # you will have to set the variable as an array. 367 | # 368 | # PLEASE NOTE 369 | # Each email address undergoes a check to verify it is properly 370 | # formatted. 371 | # ------------------------------------------------------------------- 372 | # Uncomment the following Set-Variable statement and set proper 373 | # "" if you want to set the value for the 7zBackup script. 374 | # ------------------------------------------------------------------- 375 | # Set-Variable -Name BkNotifyLogCc -Value "someemail@somedomain.com" -Scope 1 376 | # - or - 377 | # Set-Variable -Name BkNotifyLogCc -Value @("someemail@somedomain.com", "someotheremail@somedomain.com") -Scope 1 378 | 379 | # -------------------------------------------------------------------- 380 | # Variable : BkNotifyLogBcc 381 | # Argument Name : --notifyBcc 382 | # Description : Holds the email address(es) to send the report 383 | # of operations in Bcc. 384 | # Comments 385 | # ------------------------------------------------------------------- 386 | # Use this argument to set a single email address, or a list of email 387 | # addresses, which will receive the detailed report of operations. 388 | # If you mean to address the report to a single email address then 389 | # you will want to set the variable as a normal string. 390 | # If you mean to have multiple addresses to send the report to, then 391 | # you will have to set the variable as an array. 392 | # 393 | # PLEASE NOTE 394 | # Each email address undergoes a check to verify it is properly 395 | # formatted. 396 | # ------------------------------------------------------------------- 397 | # Uncomment the following Set-Variable statement and set proper 398 | # "" if you want to set the value for the 7zBackup script. 399 | # ------------------------------------------------------------------- 400 | # Set-Variable -Name BkNotifyLogBcc -Value "someemail@somedomain.com" -Scope 1 401 | # - or - 402 | # Set-Variable -Name BkNotifyLogBcc -Value @("someemail@somedomain.com", "someotheremail@somedomain.com") -Scope 1 403 | 404 | # -------------------------------------------------------------------- 405 | # Variable : BkNotifyExtra 406 | # Argument Name : --notifyextra 407 | # Description : Specifies if you want extra info in the notification 408 | # log 409 | # Comments 410 | # ------------------------------------------------------------------- 411 | # Use this argument to set your option about having or not extra 412 | # informations in your notification log. 413 | # ExtraInfos are : the complete list of inclusions, the complete 414 | # list of exclusions and the list of exceptions (if any). In addition 415 | # the complete selection file will be sent. 416 | # Extra info delivery mode options are: 417 | # none : no extra info will be sent (default) 418 | # inline : all extra info will be written in the message body 419 | # attach : all extra info will be attached as separate files 420 | # 421 | # ------------------------------------------------------------------- 422 | # Uncomment the following Set-Variable statement and set proper 423 | # "" if you want to set the value for the 7zBackup script. 424 | # ------------------------------------------------------------------- 425 | # Set-Variable -Name BkNotifyExtra -Value "< none | inline | attach >" -Scope 1 426 | 427 | # -------------------------------------------------------------------- 428 | # Variable : BkmailSubject 429 | # Argument Name : None (you can't pass it from cli) 430 | # Description : String to use as subject for notification email 431 | # Values : 432 | # Comments 433 | # ------------------------------------------------------------------- 434 | # Self explanatory ... isn't it ? 435 | # ------------------------------------------------------------------- 436 | # Uncomment one of the following Set-Variable statement and set proper 437 | # "" if you want to set the value for the 7zBackup script. 438 | # ------------------------------------------------------------------- 439 | # Set-Variable -Name BkMailSubject -Value "7zBackup Report Host $Env:ComputerName.$Env:USERDNSDOMAIN" -Scope 1 440 | # - or - 441 | Set-Variable -Name BkMailSubject -Value "7zBackup Report Host $Env:ComputerName" -Scope 1 442 | # - or - 443 | # Set-Variable -Name BkMailSubject -Value "7zBackup Report" -Scope 1 444 | 445 | # -------------------------------------------------------------------- 446 | # Variable : BkSmtpFrom 447 | # Argument Name : --notifyfrom 448 | # Description : Email address to send email notifications from 449 | # Values : 450 | # Comments 451 | # ------------------------------------------------------------------- 452 | # Self explanatory ... isn't it ? 453 | # ------------------------------------------------------------------- 454 | # Uncomment one of the following Set-Variable statement and set proper 455 | # "" if you want to set the value for the 7zBackup script. 456 | # ------------------------------------------------------------------- 457 | # Set-Variable -Name BkSmtpFrom -Value ($Env:UserName + "@" + $Env:UserDNSDomain) -Scope 1 458 | # - or - 459 | # Set-Variable -Name BkSmtpFrom -Value "" -Scope 1 460 | 461 | # -------------------------------------------------------------------- 462 | # Variable : BkSmtpRelay 463 | # Argument Name : --smtpserver 464 | # Description : The name of the smtp server to use when sending 465 | # notification emails. 466 | # Values : Host name or ip address 467 | # Comments 468 | # ------------------------------------------------------------------- 469 | # Self explanatory ... isn't it ? 470 | # ------------------------------------------------------------------- 471 | # Uncomment one of the following Set-Variable statement and set proper 472 | # "" if you want to set the value for the 7zBackup script. 473 | # ------------------------------------------------------------------- 474 | # Set-Variable -Name BkSmtpRelay -Value "" -Scope 1 475 | 476 | # -------------------------------------------------------------------- 477 | # Variable : BkSmtpPort 478 | # Argument Name : --smtpport 479 | # Description : The port to contact smtp server on 480 | # Values : integer number (default 25) 481 | # Comments 482 | # ------------------------------------------------------------------- 483 | # Self explanatory ... isn't it ? 484 | # ------------------------------------------------------------------- 485 | # Uncomment one of the following Set-Variable statement and set proper 486 | # "" if you want to set the value for the 7zBackup script. 487 | # ------------------------------------------------------------------- 488 | Set-Variable -Name BkSmtpPort -Value ([int]25) -Scope 1 489 | 490 | # -------------------------------------------------------------------- 491 | # Variable : BkSmtpUser 492 | # Argument Name : --smtpuser 493 | # Description : The user to access authenticated smtp 494 | # Values : String 495 | # Comments : If you set this remember to set smtpPass also 496 | # ------------------------------------------------------------------- 497 | # Uncomment one of the following Set-Variable statement and set proper 498 | # "" if you want to set the value for the 7zBackup script. 499 | # ------------------------------------------------------------------- 500 | # Set-Variable -Name BkSmtpUser -Value "" -Scope 1 501 | 502 | # -------------------------------------------------------------------- 503 | # Variable : BkSmtpPass 504 | # Argument Name : --smtppass 505 | # Description : The password to use for authenticated smtp 506 | # Values : String 507 | # Comments : If you set this remember to set smtpUser also 508 | # ------------------------------------------------------------------- 509 | # Uncomment one of the following Set-Variable statement and set proper 510 | # "" if you want to set the value for the 7zBackup script. 511 | # ------------------------------------------------------------------- 512 | # Set-Variable -Name BkSmtpPass -Value "" -Scope 1 513 | 514 | # -------------------------------------------------------------------- 515 | # Variable : BkSmtpSsl 516 | # Argument Name : --smtpssl 517 | # Description : Whether or not to enable Ssl over smtp 518 | # Values : True or False 519 | # Comments 520 | # ------------------------------------------------------------------- 521 | # Self explanatory ... isn't it ? 522 | # ------------------------------------------------------------------- 523 | # Uncomment one of the following Set-Variable statement and set proper 524 | # "" if you want to set the value for the 7zBackup script. 525 | # ------------------------------------------------------------------- 526 | # Set-Variable -Name BkSmtpSsl -Value ($False) -Scope 1 527 | 528 | # -------------------------------------------------------------------- 529 | # Variable : BkPreAction 530 | # Argument Name : --pre 531 | # Description : Sets the action to invoke before scanning process 532 | # takes place. Can be, for example, used to create 533 | # additional data to backup 534 | # Values : Either a pws file or a script block 535 | # 536 | # Comments 537 | # ------------------------------------------------------------------- 538 | # Please take into account that this code must return output to the 539 | # calling script if you want the action to be logged properly. 540 | # 541 | # ------------------------------------------------------------------- 542 | # Uncomment one of the following Set-Variable statement and set proper 543 | # "" if you want to set the value for the 7zBackup script. 544 | # ------------------------------------------------------------------- 545 | # Set-Variable -Name BkPreAction -Value "C:\MyScripts\SomeOtherScript.ps1" -Scope 1 546 | # - or, say for example you want to backup your sql express databases - 547 | # Set-Variable -Name BkPreAction -Value { 548 | 549 | # [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.ConnectionInfo'); 550 | # [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Management.Sdk.Sfc'); 551 | # [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO'); 552 | # # Required for SQL Server 2008 (SMO 10.0). 553 | # [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMOExtended'); 554 | # $Server = ".\SQLEXPRESS"; 555 | # $Dest = "D:\somepath\"; 556 | # $srv = New-Object Microsoft.SqlServer.Management.Smo.Server $Server; 557 | # # If missing set default backup directory. 558 | # If ($Dest -eq "") { $Dest = $server.Settings.BackupDirectory + "\" }; 559 | 560 | # # Clean Dest directory from any previous backup 561 | # Remove-Item $Dest -Recurse -Force -ErrorAction SilentlyContinue 562 | # Start-Sleep 5 563 | # New-Item $Dest -ItemType Directory | Out-Null 564 | 565 | # Write-Output ("Started at: " + (Get-Date -format yyyy-MM-dd-HH:mm:ss)); 566 | # # Full-backup for every database 567 | # foreach ($db in $srv.Databases) 568 | # { 569 | # If($db.Name -ne "tempdb") # Non need to backup TempDB 570 | # { 571 | # Write-Output ("Backup of $db started") 572 | # $timestamp = Get-Date -format yyyy-MM-dd-HH-mm-ss; 573 | # $backup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup"); 574 | # $backup.Action = "Database"; 575 | # $backup.Database = $db.Name; 576 | # $backup.Devices.AddDevice($Dest + $db.Name + "_full_" + $timestamp + ".bak", "File"); 577 | # $backup.BackupSetDescription = "Full backup of " + $db.Name + " " + $timestamp; 578 | # $backup.Incremental = 0; 579 | # # Starting full backup process. 580 | # $backup.SqlBackup($srv); 581 | # # For db with recovery mode <> simple: Log backup. 582 | # If ($db.RecoveryModel -ne 3) 583 | # { 584 | # $timestamp = Get-Date -format yyyy-MM-dd-HH-mm-ss; 585 | # $backup = New-Object ("Microsoft.SqlServer.Management.Smo.Backup"); 586 | # $backup.Action = "Log"; 587 | # $backup.Database = $db.Name; 588 | # $backup.Devices.AddDevice($Dest + $db.Name + "_log_" + $timestamp + ".trn", "File"); 589 | # $backup.BackupSetDescription = "Log backup of " + $db.Name + " " + $timestamp; 590 | # #Specify that the log must be truncated after the backup is complete. 591 | # $backup.LogTruncation = "Truncate"; 592 | # # Starting log backup process 593 | # $backup.SqlBackup($srv); 594 | # }; 595 | # }; 596 | # }; 597 | # Write-Output ("Finished at: " + (Get-Date -format yyyy-MM-dd-HH:mm:ss)); 598 | # } 599 | 600 | # -------------------------------------------------------------------- 601 | # Variable : BkPostAction 602 | # Argument Name : --post 603 | # Description : Sets the action to invoke after the archiving 604 | # process completes. Can be used for example to 605 | # move or upload the generated archive 606 | # Values : Either a pws file or a script block 607 | # 608 | # Comments 609 | # ------------------------------------------------------------------- 610 | # Please take into account that this code must return output to the 611 | # calling script if you want the action to be logged properly. 612 | # 613 | # ------------------------------------------------------------------- 614 | # Uncomment one of the following Set-Variable statement and set proper 615 | # "" if you want to set the value for the 7zBackup script. 616 | # ------------------------------------------------------------------- 617 | # Set-Variable -Name BkPostAction -Value "C:\MyScripts\SomeOtherScript.ps1" -Scope 1 618 | # - or, say for example you want to upload your archive via ftp - 619 | # Set-Variable -Name BkPostAction -Value { 620 | 621 | # $RemoteTarget = "ftp://user:password@/$BkArchiveName" 622 | # $numTries = 0; $maxTries = 5 623 | # $status = $False 624 | # do { 625 | # Try { 626 | # Write-Output ("Trying to upload file {0} : attempt {1}" -f $BkArchiveName, ($numTries + 1)) 627 | # $webclient = New-Object -TypeName System.Net.WebClient 628 | # $uri = New-Object -TypeName System.Uri -ArgumentList $RemoteTarget 629 | # $webclient.UploadFile($uri, $OutFile) 630 | # $status = $true 631 | # } Catch { 632 | # Write-Output $_.Exception.Message 633 | # $numTries++ 634 | # Start-Sleep -s 5 635 | # } 636 | # } 637 | # While ($numTries -le $maxTries -and $status -eq $false) 638 | # If($status) { 639 | # Write-Output ("File {0} succesfully uploaded" -f $BkArchiveName) 640 | # } Else { 641 | # Write-Output ("Could not upload {0}" -f $BkArchiveName) 642 | # } 643 | 644 | #} -------------------------------------------------------------------------------- /7zBackup.ps1: -------------------------------------------------------------------------------- 1 | # ******************************************************************** 2 | # IMPORTANT: This script is not Officially supported in any way ! 3 | # Use it at your own risk !!! 4 | # ******************************************************************** 5 | # NAME : 7zBackup.ps1 6 | # DESCRIPTION : This script will help you automate the backup process 7 | # of your data using 7zip compression program. 8 | # When job is done a detailed report is produced. 9 | # OS : Microsoft Windows 2000 (NOT tested) 10 | # Microsoft Windows XP (tested) 11 | # Microsoft Windows 2003 (tested) 12 | # Microsoft Windows Vista (tested) 13 | # Microsoft Windows 7 (tested) 14 | # Microsoft Windows 2008 (tested) 15 | # Microsoft Windows 8 (tested) 16 | # Microsoft Windows 8.1 (tested) 17 | # Microsoft Windows 10 (tested) 18 | # Microsoft Windows 2008 (tested) 19 | # Microsoft Windows 2012 (tested) 20 | # REQUIREMENTS : 7zip (http://www.7-Zip.org/download.html) 21 | # Junction v1.05 (http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx) 22 | # NTFS File System with support for junctions or 23 | # symbolic links 24 | # -------------------------------------------------------------------- 25 | # Give credit to the following contributors: 26 | # (please do not remove - add your name if you contribute) 27 | # 28 | # * Andrea Lanfranchi - Anlan (http://www.anlan.com) 29 | # 30 | # -- Version History – 31 | # X.XXX YYYYMMDD Author Description 32 | # ------------- -------- -------- -------------------------------------------------- 33 | $version = "01.000-beta" # 20091104 Anlan First release 34 | $version = "01.001-beta" # 20091208 Anlan Minor Fixes 35 | $version = "01.002-beta" # 20091224 Anlan Clear Archive Bit now uses Set-ItemProperty 36 | # ProcessFolder now implements -force switch to discover hidden files 37 | # 38 | $version = "1.5-Stable" # 20091229 Anlan --workdir switch has been dismissed 39 | # To prevent the occurrence of PathTooLong Exception as much 40 | # as possible now the script will generate a short 41 | # randomly named directory in the root of the drive 42 | # specified by the --workdrive switch which has now 43 | # become mandatory 44 | # Complete rewrite of the selection process to speed it up 45 | # and new directives to stop recursion and to honor (or not) 46 | # junctions during scanning process 47 | # 48 | $version = "1.5.1-Stable" # 20091229 Anlan Minor Fixes : $totalBytes strongly typed to [int64] 49 | # Get-ChildItem in ProcessFolder now with -ErrorAction Stop 50 | # 51 | $version = "1.5.2-Stable" # 20091231 Anlan Minor : Revised error handling in ProcessFolder Function 52 | # Minor : ProcessFolder now Silently Continues 53 | # New : Added support for matchincludefiles directive 54 | # New : Detailed catch of 7-Zip exit codes 55 | # New : Added control --rotate does not pass a negative number 56 | # Ui : More detailed output log with performance indicator 57 | # Speed : Adjusted default 7-Zip switches to a less aggressive 58 | # compression rate in favour of processing speed. 59 | # 60 | $version = "1.5.3-Stable" # 20100101 Anlan Speed : Removed "late" addition of info files to archive as this 61 | # causes a sensible delay on huge archives. 62 | # Ui : Log file now includes exceptions from 7-Zip (e.g file not found) 63 | # Speed : Get-Content of selection file is now in one single pass 64 | # Feat : Added support for --maxfileage and --minfileafe directives 65 | # in selection file 66 | # Feat : New argument --clearbit to enforce clearing of 67 | # "Archive" attribute on archived files 68 | # 69 | $version = "1.5.4-Stable" # 20100111 Anlan Bug : The clearing of archive bit did not work. 70 | $version = "1.5.5-Stable" # 20100111 Anlan Bug : Late clearing of archive bit after compression 71 | # may fail if the file does not exist anymore. 72 | # In addition the list of selected files has 73 | # been encoded in UTF8 to allow selection of 74 | # file names with accented letters. 75 | # 76 | $version = "1.5.6-Stable" # 20100113 Anlan Bug : Incorrect assumption on Clear Archive Bit logic 77 | # The clearing of archive bit is executed on FULL or INCR backups. 78 | # This is not correct. *It should be on FULL or DIFF backups* 79 | # 80 | $version = "1.5.7-Stable" # 20100114 Anlan Bug : Wrong encoding in 7-Zip output causes incorrect 81 | # translation on file names therefore making impossible 82 | # for the script to go and clear "A" attribute on it. 83 | # Solved by encoding in UTF8 output from 7-Zip 84 | # Ui : Statistics on selection now include Absolute and Increasing 85 | # percent of overall file sizes 86 | # 87 | $version = "1.6.0-Stable" # 20100117 Anlan Code : Complete rewrite of the main code 88 | # Feat : Added some more sophisticated error handling 89 | # Feat : All formal errors within the command line are now dropped 90 | # in a single shot. 91 | # Feat : All sensitive variables are now in a separated file 92 | # so you can replace the script with new version/relase 93 | # without the need to re-edit hardcoded values 94 | # Feat : Exceptions on selection are now included in log file 95 | # Feat : Sending of notification email now implements Try/Catch 96 | # Feat : Information about sender/recipient address for notification email 97 | # with the addition of the host to use as smtp relay can now 98 | # be passed by cli using new arguments. 99 | # Feat : You can specify location of either 7z.exe and Junction.exe 100 | # by cli using proper arguments 101 | # 102 | $version = "1.6.1-Stable" # 20100118 Anlan Bug : Clearing of archive bit did not catch errors properly 103 | # Bug : Try function does not work on PWS 2.0 as it's a statement 104 | # changed name to DoTry so we can run on both 1.0 and 2.0 105 | # Bug : Log file was not created correctly with .log extension 106 | # Feat : Now implements a VERY rudimental lock system to prevent 107 | # more than one instance of the script. 108 | # 109 | $version = "1.7.0-Stable" # 20100118 Anlan Bug : Test-Path-Writable fails on root of system drive on Windows 7 110 | # Therefore the function now accepts an optional parameter 111 | # to specify if the write test has to be performed with 112 | # a directory or a file. 113 | # Feat : Now you can specify "move" as backup type. It will remove 114 | # source files after successful archiving. 115 | # Feat : Added new directive matchcleanupfiles into selections file 116 | # This will allow the deletion of unuseful/unwanted files 117 | # during the selection phase. 118 | # Feat : CTRL+C is now intercepted by the script to allow a smooth 119 | # close of the procedure avoiding the ugly case to leave 120 | # unwanted junctions on disk. 121 | # 122 | $version = "1.7.1-Stable" # 20100426 Anlan Bug : Presence of junction.exe is wrongly referred to 7z.exe 123 | # 124 | $version = "1.7.2-Stable" # 20101206 Anlan Bug : Routine Clear-FsAttribute rewritten due to errors by 125 | # by cmdlet Get-Item while handling long paths with 126 | # many escape chars (like brackets and so on ...) 127 | # Bug : If lock file detected then script aborts leaving root 128 | # backup directory in place. 129 | # 130 | $version = "1.7.3-Stable" # 20101207 Anlan Bug : Reading back compressed files from 7zip standard output 131 | # caused non ASCII chars to be mismatched. Fixed 132 | # Changed the population of $BkCompressDetails with a 133 | # stdout redirection in UTF8 following Igor Pavolv suggestion 134 | # 135 | $version = "1.7.4-Stable" # 20110609 Anlan Code : Inserted by default /accepteula switch for junction.exe 136 | # 137 | $version = "1.7.5-Stable" # 20110830 Anlan Code : Implemented support for smtpUser and smtpPass switches 138 | # to allow smtp authentication against relay server. 139 | # Credit to marek vita (http://www.codeplex.com/site/users/view/marek_vita) 140 | # 141 | $version = "1.7.6-Stable" # 20110908 Anlan Code : Changed IsValidIp function so it can properly handle IpV6 and IpV4 142 | # addresses type. 143 | # Code : Added datetimeStamp to autogenerated logfile name so it will 144 | # not mess with other logs working 145 | # 146 | $version = "1.7.7-Stable" # 20111129 Anlan Code : Correct assumption of rotation criteria 147 | # Code : Email messages are sent even if backup is locked by previous 148 | # operation. 149 | # Code : Email priority and Suffix changed on Critical Conditions 150 | # Bug : Log file does not get deleted if operation fails 151 | # 152 | $version = "1.8.0-Stable" # 20120419 Anlan Code : Added support for Symbolic Links (MKLINK) for 153 | # Windows Vista / 7 / 2008 +. 154 | # Now it supports remote UNC paths as source for backups 155 | # 156 | $version = "1.8.1-Stable" # 20120819 Anlan Code : New work switch maxrecursionlevel to limit recursion depth 157 | # in searching files. 158 | # Code : rotate argument switch can now be set in selection file too 159 | # Code : prefix argument switch can now be set in selection file too 160 | # Code : prefix argument switch is checked against invalid file name chars 161 | # 162 | $version = "1.8.2-Stable" # 20120825 Anlan Code : Email report now has Exceptions Include and Exlude lists as 163 | # attachments. 164 | # 165 | $version = "1.8.3-Stable" # 20121018 Anlan Code : new smtpssl to enable Ssl over smtp transport 166 | # 167 | $version = "1.8.4-Stable" # 20130107 Anlan Code : Removed DoTry function in favour of native Try-Catch-Finally Statement 168 | # Bug : Function SendNotificationMail do not properly dispose objects so 169 | # root directory can not be safely deleted 170 | # 171 | $version = "1.9.0-Stable" # 20130112 Anlan Feat : Rewritten the launcher of 7zip with Start-Process. Now you can monitor 172 | # the progress of 7zip's job. 173 | # Code : Improved the effectiveness of interception of CTRL+C so you can 174 | # safely interrupt the execution of the script even while 7zip is running. 175 | # Code : Workdrive is checked for NTFS filesystem 176 | # 177 | $version = "1.9.5-Stable" # 20131018 Anlan Feat : Rewritten the launcher of 7zip with *old* fashioned batch. Better 178 | # monitoring of exit codes. Now works ok with PWS 2.0 179 | # Feat : New argument --notifyextra to drive the way extra information is 180 | # delivered with the notification log 181 | # Bug : NoFollowJunctions switch was inverted 182 | # Feat : Added new directive maxfilesize and minfilesize to enhance file selection 183 | # based upon their size 184 | $version = "1.9.6-Stable" # 20131126 Anlan Bug : Typo in variable naming smtpPass which caused authenticated SMTP to fail 185 | $version = "1.9.7-Stable" # 20140205 Anlan Bug : Get-ChildItem in ProcessFolder routine now uses -LiteralPath to allow 186 | # processing of folder names with square brackets in it. 187 | # 188 | $version = "1.9.8-Stable" # 20140814 Anlan Feat : Now lock file holds process id and RootDir 189 | # Subsequent launches of script will check if "old" process is still 190 | # running and responding or if it is stuck. 191 | # 192 | $version = "1.9.9-Stable" # 20141114 Anlan Bug : Parameter --7zbin should be --7zipbin. Added both for backwards 193 | # compatibility. 194 | # Bug : includeSource directives should not be processed if in wrong format 195 | # Feat : try to include empty directories (if writable) 196 | # 197 | $version = "1.9.10-Stable" # 20150217 Anlan Bug : Argument --notifyextra incorrectly values variable BkArchiveType 198 | # 199 | $version = "1.9.11-Stable" # 20151022 Anlan Bug : For Windows 10 the statement $Host.UI.RawUI.FlushInputBuffer 200 | # should be $Host.UI.RawUI.FlushInputBuffer() 201 | $version = "1.10.0-Stable" # 20151122 Anlan Feat : Added support for 7zip 15.x 202 | # Code : Some code refactoring 203 | $version = "1.10.1-Stable" # 20151130 Anlan Bug : Wrong parsing of output files 204 | # Code : Some code refactoring 205 | $version = "1.10.2-Stable" # 20151210 Anlan Code : Some code refactoring to improve speed 206 | # 207 | $version = "1.10.3-Stable" # 20160425 Anlan Code : Typo in LasWriteTime instead of LastWriteTime 208 | # Feat : MaxFileAge and MinFileAge now support Decimal 209 | # Feat : MaxFileAge and MinFileAge can be passed by CLI 210 | # 211 | $version = "2.0.1-Stable" # 20160608 Anlan Code : Since version 15.x of 7-zip it can now save natively emtpy dirs 212 | # therefore no need to create dummy files 213 | # Code : Removed the check for pairs of command arguments. 214 | # Now the parser checks properly also for switch arguments 215 | # Code : Refactored Main Scanning Routine to eliminate Stack Overflow 216 | # Feat : Removed the limit of 100 for maxdepth 217 | # Feat : Added new command line switch --dry 218 | # This causes the script to go through all scanning directives 219 | # but no compression or archiving is perfomed. 220 | # Bug : rotation of archives might delete directories with same name 221 | # Included check for "is not a PSContainer" 222 | # Feat : --emptydirs is now a switch argument 223 | # Feat : addedd --compression argument 224 | # Feat : Removed the parsing of BkSwitches 225 | # Feat : addedd --pre and --post action switches to enable 226 | # the execution of personalized scripts before and after 227 | # the archiving process 228 | # Bug : MaxFileAge and MinFileAge are fixed as double 229 | # Feat : Archive name gets composed with trailing seconds 230 | # Feat : Refactored writing of logs and details with StreamWriters 231 | # instead of Out-File. Now scanning speed is 5x up to 20x 232 | # Code : Refactored async launch of 7-zip process to get proper return core 233 | # Feat : --maxfileage and --minfileage can now be passed as switches 234 | # Feat : --maxfilesize and --minfilesize can now be passed as switches 235 | # Feat : --pre and --post switches can invoke pws actions 236 | # Feat : --threads switch can control resource usage by 7-zip 237 | # 238 | $version = "2.0.2-Stable" # 20160722 Anlan Bug : Improper output when Send-Notification is invoked 239 | # Feat : added --solid switch to enable or disable solid archives 240 | # Feat : compression / solid mode / threads can be also set in selection file 241 | # Code : adjusted checks on removal of reparse points 242 | # Code : adjusted count of maximum threads on single core sockets 243 | # Feat : added switch -mhe for password protected archives 244 | # 245 | $version = "2.0.3-Stable" # 20160809 Anlan Code : Reimplemented Set-Alias for Junction.exe binary 246 | # Code : Parsing of directives from selection file now takes precedence over 247 | # switches and parameters 248 | $version = "2.0.4-Stable" # 20161111 Anlan Code : Minor code fixes 249 | # Feat : Added support for volumized archives 250 | $version = "2.0.5-Stable" # 20171102 PWalker Code : Forced clear Archive bit for Hidden files 251 | # Feat : Some Debug info 252 | $version = "2.0.6-Stable" # 20171105 Anlan Code : Adjusted lowering of Archive Bits for non ASCII characters 253 | # 254 | $version = "2.0.7-Stable" # 20171113 Anlan Feat : Emission of warning on low space for destpath directory 255 | # Code : Adjusted emission message on presence of lock file 256 | # Code : Adjusted calculation of cores/threads 257 | # Code : Cleanup 258 | # 259 | $version = "2.0.8-Stable" # 20171121 Anlan Feat : Logger has been embedded as internal string builder 260 | # This helps notifying for parameters errors 261 | $version = "2.1.0-Stable" # 20171127 Anlan Code : Adjusted calc of threads over cores 262 | # Anlan Feat : Added matchcleanupdirs directive in selection to remove unwanted 263 | # or temporary directories during scan USE WITH GREAT CARE !!!! 264 | # Code : Amended some typos about Bytes and Mbytes 265 | $version = "2.1.1-Stable" # 20171128 Anlan Feat : Added some useful about archives occupation on target 266 | # Anlan Feat : Addedd support for notify addresses in CC and BCC 267 | # Anlan Feat : Better organization of output 268 | # 269 | $version = "2.1.2-Stable" # 20180322 Anlan Feat : Adjusted clear archive bit 270 | # 271 | $version = "2.1.3-Stable" # 20200514 Anlan Code : Enclosed [console]::TreatControlCAsInput in Try Catch block 272 | # as it may throw is console is launched with stdin redirection 273 | $version = "2.1.4-Stable" # 20200824 Anlan Code : Speed up PostArchiving a little bit using a range iterator 274 | 275 | # !! For a new version entry, copy the last entry down and modify Date, Author and Description 276 | # 277 | # This program is free software; you can redistribute it and/or modify 278 | # it under the terms of the GNU General Public License as published by 279 | # the Free Software Foundation; either version 2 of the License, or 280 | # (at your option) any later version. 281 | # 282 | # This program is distributed in the hope that it will be useful, 283 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 284 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 285 | # GNU General Public License for more details. 286 | # 287 | # You should have received a copy of the GNU General Public License 288 | # along with this program; if not, write to the Free Software 289 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 290 | # 291 | # Those who do not know how to use snail mail: The GPL is here: 292 | # http://www.gnu.org/licenses/gpl.html 293 | 294 | # -------------------------------------------------------------------- -------------------------------------------------------------------- 295 | # DO NOT CHANGE ANYTHING BELOW THIS POINT UNLESS YOU'RE A DEVELOPER I Repeat DO NOT CHANGE ANYTHING BELOW THIS POINT UNLESS YOU'RE A DEVELOPER 296 | # AND EXACTLY KNOW WHAT YOU'RE DOING I Repeat AND EXACTLY KNOW WHAT YOU'RE DOING 297 | # -------------------------------------------------------------------- -------------------------------------------------------------------- 298 | 299 | # -------------------------------------------------------------------- 300 | # Init Some Vars to be used globally in the script 301 | # -------------------------------------------------------------------- 302 | $Error.Clear() 303 | $ErrorActionPreference = "SilentlyContinue" 304 | 305 | Set-Variable -Name "MyContext" -Value ([hashtable]::Synchronized(@{})) -Scope Script 306 | $MyContext.Name = $MyInvocation.MyCommand.Name 307 | $MyContext.Definition = $MyInvocation.MyCommand.Definition 308 | $MyContext.Directory = (Split-Path (Resolve-Path $MyInvocation.MyCommand.Definition) -Parent) 309 | $MyContext.StartDir = (Get-Location -PSProvider FileSystem).ProviderPath 310 | $MyContext.WinVer = (Get-WmiObject Win32_OperatingSystem).Version.Split(".") 311 | $MyContext.PSVer = [int]$PSVersionTable.PSVersion.Major 312 | $MyContext.Cancelling = $False 313 | $MyContext.DummyFile = ".7zb" 314 | $MyContext.Logger = New-Object -TypeName System.Text.StringBuilder 315 | 316 | $headerText = @" 317 | 318 | ------------------------------------------------------------------------------ 319 | 320 | 7zBackup.ps1 ver. $version (https://github.com/Isiweb/7zBackup) 321 | 322 | ------------------------------------------------------------------------------ 323 | 324 | "@ 325 | 326 | $helpText = @" 327 | Usage : .\7zBackup.ps1 --type < full | incr | diff | copy | move > 328 | --selection < full path to file name > 329 | --destpath < destination path > 330 | [--jbin < path to Junction.exe > ] 331 | 332 | -- Job specific switches -- 333 | [--dry] 334 | [--workdrive < working drive letter >] 335 | [--rotate < number >] 336 | [--logfile < filename >] IGNORED since 2.0.8 337 | [--pre < filename | `{scriptblock`} >] 338 | [--post < filename | `{scriptblock`} >] 339 | 340 | -- Selection specific switches -- 341 | [--maxdepth < number > ] 342 | [--maxfileage < double > ] 343 | [--minfileage < double > ] 344 | [--maxfilesize < long > ] 345 | [--minfilesize < long > ] 346 | [--clearbit < True | False >] 347 | [--emptydirs] 348 | 349 | -- Archive (7-zip) specific switches -- 350 | [--prefix < string >] 351 | [--7zipbin < path to 7z.exe > ] 352 | [--archivetype < 7z | zip | tar >] 353 | [--compression < 0 | 1 | 3 | 5 | 7 | 9 >] 354 | [--threads < number >] 355 | [--solid < True | False >] 356 | [--volumes {Size}[b | k | m | g]] 357 | [--password < string >] 358 | [--encryptheaders] 359 | [--workdir < working directory > OBSOLETE] 360 | 361 | -- Notification specific switches -- 362 | [--notifyto < email1@domain`[,email2@domain`[..`]`] >] 363 | [--notifytoCc < email1@domain`[,email2@domain`[..`]`] >] 364 | [--notifytoBcc < email1@domain`[,email2@domain`[..`]`] >] 365 | [--notifyfrom < sender@domain >] 366 | [--notifyextra < none | inline | attach >] 367 | [--smtpserver < host or ip address >] 368 | [--smtpport < default 25 >] 369 | [--smtpuser < SMTPAuth's user >] 370 | [--smtppass < SMTPAuth's password >] 371 | [--smtpssl] 372 | 373 | 374 | ------------------------------------------------------------------------------ 375 | 376 | --type Type of backup to perform: 377 | full : All files and archive bit cleared after archiving 378 | diff : Files with archive bit set. 379 | Archive bit left unchanged after backup. 380 | incr : Files with archive bit set. 381 | Archive bit cleared after backup. 382 | copy : Same as FULL but leave archive bits unchanged 383 | move : All files matching selection criteria regardless 384 | their Archive bit status. After succesful operation 385 | archived files are deleted from their original 386 | location. Use with great care. 387 | 388 | --selection Full path to file containing the selection criteria 389 | 390 | --destpath Full path to destination media which will contain the archive. 391 | Ensure it will be on a drive with sufficient space to 392 | contain all the data. Can be a UNC path. 393 | 394 | --workdrive Drive letter to use for creation of root junction point. 395 | If not set the script will use the drive associated to 396 | the TEMP environment variable. It MUST be a valid 397 | drive letter with the exclusion of A and B. Drive associated 398 | to this letter must have NTFS file system and it`'s root 399 | must be writable. 400 | 401 | --archivetype The type of archive you want to create. 402 | 7z : default format with better compression 403 | zip : very compatible with other programs 404 | tar : unix and linux compatible but only archiving (no compression) 405 | 406 | --compression The level of compression you want to achieve. 407 | Possible values are [0 | 1 | 3 | 5 | 7 | 9 ]. 408 | where lower values mean almost no compression and fast 409 | archiving while higher values mean the opposite. 410 | If omitted 7zip will use default settings 411 | 412 | --threads Number of threads 7zip is allowed to use. If not set then 413 | 7zip will try to adopt one thread per core. Set this value 414 | to 1 or 0 to disable multithreading. 415 | 416 | --solid Sets wether or not 7z archives should endorse solid format 417 | By default 7z archives endorse solid format. Refer to 418 | 7-zip documentation to understand what are solid archives. 419 | 420 | --volumes This command switch implements the -v switch provided by 421 | 7-zip. You can pass a single value or a list of values 422 | comma separated. 423 | 424 | --rotate This value must be a number and indicates the number of 425 | archives that should remain on disk after successful 426 | archiving. For example if you set --rotation 3 on a 427 | full archiving operation it means that the newest 3 full 428 | archives will be kept on disk while the oldest (if any) 429 | will be deleted. If this value is NOT set then ALL the 430 | generated archives will be kept on disk. Please be advised 431 | that in such case your target media will be likely get 432 | out of space soon. It can be specified either as command argument, 433 | or in the hardcoded vars file, or in the selection file. 434 | 435 | --maxdepth This value si a zero-based index limiting the depth of recursion 436 | while scanning in search of files to backup. Valid values are 437 | positive integers. It can be specified either as command argument 438 | or in the hardcoded vars file, or in the selection file. 439 | 440 | --clearbit In backup operations of type FULL or DIFF the Archive attribute 441 | of backupped files is cleared. If you do not want the script 442 | to do this simply pass --clearbit False. On the other hand 443 | if you do want to clear the attribute even in other backup 444 | types then pass --clearbit True 445 | 446 | --emptydirs By design an archive will hold only files, not directories. 447 | Therefore the script will simply not find anything to backup 448 | in an empty directory. If you wish the archive to have the 449 | indication of empty directories also simply enable this switch. 450 | It will drop a dummy placeholder file in the empty dir therefore 451 | allowing the compressor to select it. 452 | This is a switch argument 453 | 454 | --password Use this switch if you want to password protect your 455 | archive. No spaces in passwords please. 456 | 457 | --prefix The prefix to use to generate the archive name. 458 | 459 | --workdir SUPERSEDED (will be simply ignored) 460 | Directory which will be used as working area. 461 | Must be on an NTFS file system. If none is given then 462 | the procedure will try to use the one in environment's 463 | TEMP variable. 464 | 465 | --7zipbin Specify full path to 7z.exe. 466 | If the argument is not provided the script will try to 467 | locate 7z.exe in program files folders 468 | 469 | --jbin Specify full path to Junction.exe. 470 | If the argument is not provided the script will try to 471 | locate Junction.exe in program files folders 472 | This parameter is optional when the script is invoked 473 | on Windows systems which support MKLINK. 474 | 475 | --logfile Where to log backup operations. If empty will be 476 | generated automatically. 477 | 478 | --notifyto Use this argument to set a list of email addresses who 479 | will receive an email with a copy of the logfile. 480 | You can specify multiple addresses separated by commas. 481 | If you set this switch be sure to edit the script and 482 | insert propervalues in variables `$smtpFrom `$smtpRelay and `$smtpPort 483 | 484 | --notifytoCc As notifyto but in Carbon Copy 485 | 486 | --notifytoBcc As notifyto but in Blind Carbon Copy 487 | 488 | --notifyfrom Use this argument to set the proper address to use as 489 | sender address when sending out email notifications 490 | 491 | --notifyextra Use this argument to set the way this script will include 492 | extra informations in the notification message. 493 | none : no extra informations 494 | inline : extra informations in the body of the message 495 | attach : extra informations attached to the message 496 | 497 | --smtpserver Host name or IP address of the server to use 498 | 499 | --smtpport Port number of the smtp server (Default is 25) 500 | 501 | --smtpuser Smtp's authenticated user (if smtpauth required) 502 | 503 | --smtppass Smtp's authenticated password (if smtpauth required) 504 | 505 | --smtpssl Wheather or not smtp transport requires ssl 506 | This is a switch argument 507 | 508 | --dry Complete the process without creating any archive file 509 | nor changing/deleting/clearing any file 510 | 511 | --pre Pointer to a pws script or a script block to be execute 512 | before scanning process starts 513 | 514 | --post Pointer to a pws script or a script block to be execute 515 | after archiving procedure completes regardless it's been 516 | succesfull or not 517 | ----------------------------------------------------------------------- 518 | 519 | "@ 520 | 521 | # ==================================================================== 522 | # Start Functions Library 523 | # ==================================================================== 524 | 525 | # Legend for Attributes bits on files 526 | # - Normal ....... (n) ==> 0 527 | # - Hidden ....... (h) ==> 2 528 | # - ReadOnly ..... (r) ==> 1 529 | # - System ....... (s) ==> 4 530 | # - Directory .... (d) ==> 16 531 | # - Archive ...... (a) ==> 32 532 | # - ReparsePoint . (j) ==> 1024 533 | 534 | # Load Attributes Names in array for usage in functions 535 | #$attrNames = [enum]::getNames([System.IO.FileAttributes]); 536 | 537 | # ----------------------------------------------------------------------------- 538 | # Function : Do-PostAction 539 | # ----------------------------------------------------------------------------- 540 | # Description : Executes a job after execution 541 | # Returns : 542 | # Credits : 543 | # ----------------------------------------------------------------------------- 544 | Function Do-PostAction { 545 | 546 | # -------------------------------------------------------------------------------- 547 | # Execute post Action if we have any 548 | # -------------------------------------------------------------------------------- 549 | If(Test-Variable "BkPostAction") { 550 | 551 | Trace " Invoking Post-Action (Output follows if any)" 552 | Trace " ------------------------------------------------------------------------------" 553 | Try { 554 | & $BkPostAction 2>&1 | Set-Variable -Name "postActionOutput" -Scope Script 555 | $postActionOutput | ForEach-Object { 556 | Trace " $_" 557 | } 558 | } Catch { 559 | Trace " $_.Exception.Message" 560 | } 561 | Trace " ------------------------------------------------------------------------------" 562 | Trace " " 563 | 564 | } 565 | 566 | } 567 | 568 | # ----------------------------------------------------------------------------- 569 | # Function : Check-CTRLCRequest 570 | # ----------------------------------------------------------------------------- 571 | # Description : Checks whether or not the user hit CTRL + C to request 572 | # script cancel 573 | # Parameters : 574 | # Returns : $True / $False 575 | # Credits : 576 | # ----------------------------------------------------------------------------- 577 | Function Check-CTRLCRequest { 578 | 579 | If($MyContext.Cancelling -ne $True) { 580 | If($Host.UI.RawUI.KeyAvailable -and [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character -eq 3) { 581 | $MyContext.Cancelling = $True 582 | Trace " " 583 | Trace " User requested to abort ... " 584 | Trace " " 585 | } 586 | } 587 | $Host.UI.RawUI.FlushInputBuffer() 588 | Write-Output ($MyContext.Cancelling) 589 | } 590 | 591 | 592 | # ----------------------------------------------------------------------------- 593 | # Function : Check-FsAttribute 594 | # ----------------------------------------------------------------------------- 595 | # Description : Checks for the presence of an attribute on a FileSystem object 596 | # Parameters : [string]itemFullName - The name of the item to check 597 | # [string]attrName - The name of the attribute to look for 598 | # Returns : $True / $False 599 | # Credits : http://scriptolog.blogspot.com/2007/10/file-attributes-helper-functions.html 600 | # ----------------------------------------------------------------------------- 601 | Function Check-FsAttribute { 602 | param([string]$itemFullName = $(throw "You must provide an item name"), 603 | [string]$attrName = $(throw "You must provide an attribute name")) 604 | 605 | $item = Get-Item -literalPath $itemFullName -Force 606 | Write-Output (($?) -and ($item) -and ($item.Attributes -band [System.IO.FileAttributes]::$attrName)) 607 | } 608 | 609 | # ----------------------------------------------------------------------------- 610 | # Function : Clear-FsAttribute 611 | # ----------------------------------------------------------------------------- 612 | # Description : Lowers an attribute on a file 613 | # Parameters : [string]fileFullName - The name of the File to work on 614 | # [string]attrName - The name of the attribute to lower 615 | # Returns : $True / $False 616 | # Credits : http://scriptolog.blogspot.com/2007/10/file-attributes-helper-functions.html 617 | # ----------------------------------------------------------------------------- 618 | Function Clear-FsAttribute { 619 | param([string]$fileFullName = $(throw "You must provide a file name"), 620 | [string]$attrName = $(throw "You must provide an attribute name")) 621 | 622 | # Do Nothing in DryRun mode 623 | If($BkDryRun) { Write-Output $True; Return } 624 | 625 | # Lower attribute bit 626 | # TO-DO ... extremely slow 627 | 628 | $item = (Get-Item -LiteralPath $fileFullName -Force) 629 | If(!($?)) { 630 | Write-Output $False 631 | } Else { 632 | If(($item.Attributes -band [System.IO.FileAttributes]::$attrName)) { 633 | $item = ( $item | Set-ItemProperty -Name Attributes -Value ($item.Attributes -bXor [System.IO.FileAttributes]::$attrName) -Force -PassThru) 634 | Write-Output (($?) -and ($item)) 635 | Return 636 | } 637 | Write-Output $True 638 | } 639 | 640 | } 641 | 642 | # ----------------------------------------------------------------------------- 643 | # Function : Clear-Script 644 | # ----------------------------------------------------------------------------- 645 | # Description : Cleans all files created by the script and leaves the system 646 | # in a state which allows another go. 647 | # Parameters : - 648 | # Returns : Nothing 649 | # ----------------------------------------------------------------------------- 650 | Function Clear-Script { 651 | 652 | #Ensure file stream writers are closed 653 | $SWriters.GetEnumerator() | ForEach-Object { 654 | Try { 655 | $_.Value.Flush() 656 | $_.Value.Close() 657 | $_.Value.Dispose() 658 | } Catch {} 659 | } 660 | 661 | 662 | If ((Test-Variable "cmdLineBatch")) {if ((Test-Path ($cmdLineBatch))) { Remove-Item -LiteralPath $cmdLineBatch | Out-Null }} 663 | If ((Test-Variable "BkLockFile")) {if ((Test-Path ($BkLockFile))) { Remove-Item -LiteralPath $BkLockFile | Out-Null }} 664 | Set-Location ($MyContext.StartDir) 665 | If ((Test-Path -Path ($BkRootDir) -PathType Container)) { Remove-RootDir $BkRootDir | Out-Null } 666 | 667 | Try { 668 | [console]::TreatControlCAsInput = $False 669 | } Catch {} 670 | 671 | } 672 | 673 | 674 | # ----------------------------------------------------------------------------- 675 | # Function : IsValidEmailAddress 676 | # ----------------------------------------------------------------------------- 677 | # Description : This function is used to check if a given string is an email 678 | # address. 679 | # Parameters : [string]emailAddress - The string to check 680 | # Returns : $True / $False 681 | # ----------------------------------------------------------------------------- 682 | Function IsValidEmailAddress { 683 | param([string]$emailAddress = $(throw "You must provide an address")) 684 | Write-Output ($emailAddress -match "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$") 685 | } 686 | 687 | # ----------------------------------------------------------------------------- 688 | # Function : IsValidHostName 689 | # ----------------------------------------------------------------------------- 690 | # Description : This function is used to check if a given string is a 691 | # valid host name. 692 | # Parameters : [string]hostName - The string to check 693 | # Returns : $True / $False 694 | # ----------------------------------------------------------------------------- 695 | Function IsValidHostName { 696 | param([string]$hostName = $(throw "You must provide an host name")) 697 | Write-Output ($hostName -match "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$") 698 | } 699 | 700 | # ----------------------------------------------------------------------------- 701 | # Function : GetDestPathFreeSpace 702 | # ----------------------------------------------------------------------------- 703 | # Description : This function is used to check how much available space is 704 | # available on destpath. 705 | # Parameters : [string]DestPath - The Path To Check 706 | # Returns : Long Integer 707 | # ----------------------------------------------------------------------------- 708 | Function GetDestPathFreeSpace { 709 | param([string]$target = $(throw "You must provide a location to check")) 710 | 711 | If($target -imatch "^\\\\") { 712 | 713 | While($true) { 714 | $parent = (Split-Path -Path $target -Parent) 715 | If($parent) { $target = $parent } Else { break } 716 | } 717 | Write-Output ([int64]((new-object -com scripting.filesystemobject).getdrive($target).availablespace)) 718 | 719 | } Else { 720 | 721 | Write-Output ([int64]((new-object -com scripting.filesystemobject).getdrive($target.Substring(0,1)).availablespace)) 722 | 723 | } 724 | } 725 | 726 | # ----------------------------------------------------------------------------- 727 | # Function : IsValidIPAddress 728 | # ----------------------------------------------------------------------------- 729 | # Description : This function is used to check if a given string is an IP 730 | # address. 731 | # Parameters : [string]ipAddress - The string to check 732 | # Returns : $True / $False 733 | # ----------------------------------------------------------------------------- 734 | Function IsValidIPAddress { 735 | param([string]$ipAddress = $(throw "You must provide an address")) 736 | Set-Variable -name "Ip" -value ([System.Net.IPAddress]::Parse("127.0.0.1")) -scope Local 737 | Write-Output ([System.Net.IPAddress]::TryParse($ipAddress, [ref]$Ip)) 738 | } 739 | 740 | # ----------------------------------------------------------------------------- 741 | # Function : Make-Junction 742 | # ----------------------------------------------------------------------------- 743 | # Description : Creates a Junction by the means of SysInternals' Junction.exe 744 | # Parameters : [string]jPath - Full path to the name of the junction 745 | # [string]jTarget - Full path to the target 746 | # Returns : $True / $False 747 | # ----------------------------------------------------------------------------- 748 | Function Make-Junction { 749 | param( 750 | [string]$jPath = $(throw "You must provide a path where to create the Junction"), 751 | [string]$jTarget = $(throw "You must provide a path to target") 752 | ) 753 | 754 | # Before we make any junction we have to test target 755 | # path exist 756 | If(Test-Path -Path $jTarget) { 757 | 758 | # Junction it (from alias) 759 | Invoke-Expression (('& "{0}" /accepteula "{1}" "{2}"') -f $BkJunctionBin, $jPath, $Target) 760 | Start-Sleep -Milliseconds 10 761 | 762 | # Test is present 763 | Write-Output (Test-Path -Path $jPath) 764 | Return 765 | 766 | 767 | } 768 | Write-Output $False 769 | } 770 | 771 | # ----------------------------------------------------------------------------- 772 | # Function : Make-SymLink 773 | # ----------------------------------------------------------------------------- 774 | # Description : Creates a Symbolic Link to Target (only available for WinVer 6+) 775 | # Parameters : [string]jPath - Full path to the name of the junction 776 | # [string]jTarget - Full path to the target 777 | # Returns : $True / $False 778 | # ----------------------------------------------------------------------------- 779 | Function Make-SymLink { 780 | param( 781 | [string]$jPath = $(throw "You must provide a path where to create the Link"), 782 | [string]$jTarget = $(throw "You must provide a path to target") 783 | ) 784 | 785 | # Before we make any junction we have to test target 786 | # path exist 787 | If(Test-Path $jTarget) { 788 | 789 | # Create Link 790 | cmd /c ("MKLINK /D `"{0}`" `"{1}`"" -f $jPath, $jTarget) | Out-Null 791 | Start-Sleep -Milliseconds 10 792 | 793 | # Test is present 794 | Write-Output (Test-Path -Path $jPath) 795 | Return 796 | 797 | } 798 | Write-Output $False 799 | } 800 | 801 | # ----------------------------------------------------------------------------- 802 | # Function : New-RootDir 803 | # ----------------------------------------------------------------------------- 804 | # Description : This function creates a new randomly named root dir 805 | # where all junctions will be created 806 | # Parameters : [string]rootPath - The name of the directory to remove 807 | # Returns : $True / $False 808 | # ----------------------------------------------------------------------------- 809 | Function New-RootDir { 810 | 811 | # Create Root Directory and place a huge README.TXT 812 | New-Item -Path $BkRootDir -ItemType Directory | Out-Null 813 | If(!$?) { 814 | Write-Output ("Unable to create directory {0}. Check permissions." -f $path) 815 | Return 816 | } Else { 817 | If([int]$MyContext.WinVer[0] -lt 6 ) { 818 | New-Item (Join-Path -Path $BkRootDir -ChildPath "__README__PLEASE__README__.txt") -type File -value "This directory contains Junctions.`nDO NOT DELETE THIS DIRECTORY AND IT'S CONTENTS USING WINDOWS EXPLORER.`nUse Junction -d to delete junctions and then safely delete the directory." | Out-Null 819 | } Else { 820 | New-Item (Join-Path -Path $BkRootDir -ChildPath "__README__PLEASE__README__.txt") -type File -value "This directory contains Symbolic Links.`nDO NOT DELETE THIS DIRECTORY AND IT'S CONTENTS USING WINDOWS EXPLORER.`nUse RD command delete symbolic links and then safely delete the directory, use cmd /c rmdir in case of using Powershell." | Out-Null 821 | } 822 | If(!$?) { 823 | Write-Output ("Can't write into {0}. Check permissions." -f $path) 824 | Return 825 | } 826 | } 827 | 828 | } 829 | 830 | # ----------------------------------------------------------------------------- 831 | # Function : PostArchiving 832 | # ----------------------------------------------------------------------------- 833 | # Description : This routine reprocess succesfully archived files 834 | # Parameters : 835 | # Returns : 836 | # ----------------------------------------------------------------------------- 837 | Function PostArchiving { 838 | 839 | Try { 840 | [console]::TreatControlCAsInput = $True 841 | } Catch {} 842 | # ----------------------------------------------------------- 843 | # Remove created placeholders if any 844 | # ----------------------------------------------------------- 845 | if ($Counters.PlaceHolders.count -gt 0) { 846 | Write-Progress -Activity "Performing post archive operations" -Status "Please wait ..." -CurrentOperation "Removing Placeholders for Empty Directories" 847 | $Counters.PlaceHolders | Remove-Item -Force | Out-Null 848 | Write-Progress -Activity "." -Status "." -Completed 849 | } 850 | If( 851 | (Check-CTRLCRequest) -Or 852 | (($BkType -ne "move") -And !($BkClearBit)) -Or 853 | ($BkDryRun) 854 | ) { Return; } 855 | 856 | # Load compress details data with respect of different log formats for different 7zip versions 857 | If(Test-Variable "BkCompressDetailItems") { Remove-Variable -Name BkCompressDetailItems} 858 | If ([int]$MyContext.SevenZBinVersionInfo.Major -gt 9) { 859 | Get-Content -Path $BkCompressDetail -Encoding UTF8 | Where-Object {$_ -match "^\+"} | Select @{Name="File";Expression={($_.Substring(2))}} | Set-Variable -Name "BkCompressDetailItems" -Scope Script 860 | } Else { 861 | Get-Content -Path $BkCompressDetail -Encoding UTF8 | Where-Object {$_ -match "^Compressing\ \ "} | Select @{Name="File";Expression={($_.Substring(13))}} | Set-Variable -Name "BkCompressDetailItems" -Scope Script 862 | } 863 | 864 | If( !($BkCompressDetailItems) -Or 865 | ($BkCompressDetailItems.Count -eq 0) -Or 866 | (Check-CTRLCRequest) 867 | ) { Return } 868 | 869 | # Remove or clear files successfully archived if necessary 870 | $MyContext.PostProcessFilesStart = Get-Date 871 | Set-Variable -Name "ArchivedItemsCount" -Value ($BkCompressDetailItems.Count) -Scope Local 872 | Set-Variable -Name "ItemsBatchSize" -Value ($ArchivedItemsCount / 100) -Scope Local 873 | Set-Variable -Name "ItemsCountDown" -Value ($ItemsBatchSize) -Scope Local 874 | Set-Variable -Name "ItemsPercent" -Value 0 -Scope Local 875 | 876 | If($BkType -eq "move") { 877 | Set-Variable -Name "OperationType" -Value "Removing" -Scope Local 878 | Trace " Deleting Successfully Archived Files" 879 | } Else { 880 | Set-Variable -Name "OperationType" -Value "Clearing" -Scope Local 881 | Trace " Clearing Archive bit for Archived Files" 882 | } 883 | Trace " -------------------------------------------" 884 | 885 | $archiveAttr = [System.IO.FileAttributes]::Archive 886 | foreach ($entry in $BkCompressDetailItems) { 887 | If(Check-CTRLCRequest -eq $True) { break; } 888 | 889 | $item = Get-Item -LiteralPath (Join-Path $BkRootDir $entry.File) -Force 890 | if($? -and $item) { 891 | If($BkType -eq "move") { 892 | $item | ? { !$_.PSIsContainer } | Remove-Item -Force | Out-Null 893 | If(!($?)) {Trace (" FAILED : {0}" -f $entry.File ); $Counters.Warnings++ } 894 | } Else { 895 | If(($item.Attributes -band $archiveAttr)) { 896 | 897 | $item = Set-ItemProperty -Path $item.FullName -Name Attributes -Value ($item.Attributes -bXOR $archiveAttr) -Force -PassThru 898 | If(!($?)) { 899 | Trace (" FAILED : {0}" -f $entry.File ); $Counters.Warnings++ 900 | } 901 | } 902 | } 903 | } Else { 904 | Write-Host " ? " + (Join-Path $BkRootDir $entry.File) 905 | } 906 | 907 | $ItemsCountDown-- 908 | If($ItemsCountDown -le 0) { 909 | $ItemsPercent++ 910 | $ItemsCountDown = $ItemsBatchSize 911 | Write-Progress -Activity "Performing post archive operations" -Status "Please wait ..." -CurrentOperation ("{0} successfully archived files" -f $OperationType) -PercentComplete ($ItemsPercent * 100) 912 | } 913 | } 914 | 915 | Write-Progress -Activity "." -Status "." -Completed 916 | $MyContext.PostProcessFilesEnd = Get-Date 917 | $MyContext.PostProcessFilesElapsed = New-TimeSpan $MyContext.PostProcessFilesStart $MyContext.PostProcessFilesEnd 918 | Trace (" Phase time : {0,0:n0} d : {1,0:n0} h : {2,0:n0} m : {3,0:n3} s" -f $MyContext.PostProcessFilesElapsed.Days, $MyContext.PostProcessFilesElapsed.Hours, $MyContext.PostProcessFilesElapsed.Minutes, ($MyContext.PostProcessFilesElapsed.Seconds + ($MyContext.PostProcessFilesElapsed.MilliSeconds/1000)) ) 919 | Trace (" Performance : {0,0:n2} files/sec`n" -f ($i / $MyContext.PostProcessFilesElapsed.TotalSeconds ) ) 920 | 921 | } 922 | 923 | # ----------------------------------------------------------------------------- 924 | # Function : ProcessFolder 925 | # ----------------------------------------------------------------------------- 926 | # Description : This is the main scanning/selection routine. 927 | # It's purpouse is to recurse all the folders below the 928 | # given root in search of files to backup 929 | # Parameters : [string]$folderPath - The name of the directory to scan 930 | # [int]$depth - Depth level reached 931 | # Returns : $True / $False 932 | # ----------------------------------------------------------------------------- 933 | Function ProcessFolder ($thisFolder) { 934 | 935 | Try { 936 | [console]::TreatControlCAsInput = $True 937 | } Catch {} 938 | # Increment number of processed folders 939 | $Counters.FoldersDone++ 940 | 941 | # Status 942 | Write-Progress -Activity ("Folder {0}" -f $thisFolder.RealName) -CurrentOperation "Checking ... " -Status ("Selected {0,0:n0} out of {1,0:n0} files in {2,0:n0} folders. {3,0:n2} MBytes to backup" -f $Counters.FilesSelected, $Counters.FilesProcessed, $Counters.FoldersDone, ($Counters.BytesSelected / 1MB )) 943 | 944 | # Verify wether or not we have to scan this folder for files or stop recursion due to regexp or maxdepth reached 945 | $scanThisPathForFiles = $True 946 | $scanThisPathForRecursion = $True 947 | If(($matchcleanupdirs) -and ($thisFolder.RelativeName -imatch $matchcleanupdirs)) { 948 | $scanThisPathForFiles = $False 949 | $scanThisPathForRecursion = $False 950 | $folderToBeNuked = (Get-Item -LiteralPath $thisFolder.RelativeName -Force | Where-Object { $_.PSISContainer -eq $true -and -not ($_.Attributes -band 1024) }) 951 | If($folderToBeNuked) { 952 | If(!$BkDryRun) { 953 | Trace (" Removing D {0} " -f $thisFolder.RealName) 954 | $folderToBeNuked | Remove-Item -Force -Recurse -ErrorVariable childDirRemoveError | Out-Null 955 | If(-Not $?) { 956 | $SWriters.Exceptions.WriteLine([string]("{0}`t{1}`t{2}" -f $Counters.Exceptions++, $childDirRemoveError.CategoryInfo.Reason, $childDirRemoveError.CategoryInfo.TargetName)) 957 | Trace (" Exception id {0} on {1} " -f $Counters.Exceptions, $thisFolder.RealName) 958 | } 959 | } Else { 960 | Trace (" Would remove {0} " -f $thisFolder.RealName) 961 | } 962 | } 963 | Return 964 | } 965 | If(($matchexcludepath) -and ($thisFolder.RelativeName -imatch $matchexcludepath)) { 966 | $scanThisPathForFiles = $False 967 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "matchexcludepath", "D", $thisFolder.RealName)) 968 | } 969 | If((Test-Variable "BkMaxDepth") -and ($thisFolder.Depth -eq [int]$BkMaxDepth)) { 970 | $scanThisPathForRecursion = $False 971 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "maxdepth", "D", $thisFolder.RealName)) 972 | } 973 | If( ($scanThisPathForRecursion) -and (($matchstoprecurse) -and ($thisFolder.RelativeName -imatch $matchstoprecurse )) ) { 974 | $scanThisPathForRecursion = $False 975 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "matchstoprecurse", "D", $thisFolder.RealName)) 976 | } 977 | 978 | If(Check-CTRLCRequest -eq $True) { return } 979 | # Early exit if we do not have to scan anything 980 | If(!$scanThisPathForFiles -and !$scanThisPathForRecursion) { return } 981 | 982 | # Get-ChildItems in folder 983 | # Status 984 | Write-Progress -Activity ("Folder {0}" -f $thisFolder.RealName) -CurrentOperation "Loading ... " -Status ("Selected {0,0:n0} out of {1,0:n0} files in {2,0:n0} folders. {3,0:n2} MBytes to backup" -f $Counters.FilesSelected, $Counters.FilesProcessed, $Counters.FoldersDone, ($Counters.BytesSelected / 1MB )) 985 | 986 | Remove-Variable childItemsScanErrors -Scope Local | Out-Null 987 | $childItems = @(Get-ChildItem -LiteralPath $thisFolder.RelativeName -Force -ErrorVariable childItemsScanErrors) 988 | If($childItemsScanErrors) { 989 | for ($i=0; $i -lt $childItemsScanErrors.count; $i++) { 990 | $realTargetName = $childItemsScanErrors[$i].CategoryInfo.TargetName.Replace($BkRootDir + "\" , "") 991 | $realTargetName = $realTargetName.Replace($realTargetName.Split("\")[0],"") 992 | $realTargetName = [string](Join-Path -Path $BkSources[$thisFolder.ContainerAlias] -ChildPath $realTargetName) 993 | $SWriters.Exceptions.WriteLine(("{0}`t{1}`t{2}" -f $Counters.Exceptions++, $childItemsScanErrors[$i].CategoryInfo.Reason, $realTargetName)) 994 | Trace (" Exception id {0} on {1} " -f $Counters.Exceptions, $realTargetName) 995 | } 996 | } 997 | 998 | # Status 999 | Write-Progress -Activity ("Folder {0}" -f $thisFolder.RealName) -CurrentOperation "Scanning ... " -Status ("Selected {0,0:n0} out of {1,0:n0} files in {2,0:n0} folders. {3,0:n2} MBytes to backup" -f $Counters.FilesSelected, $Counters.FilesProcessed, $Counters.FoldersDone, ($Counters.BytesSelected / 1MB )) 1000 | 1001 | # If it is an empty directory 1002 | If($scanThisPathForRecursion -and (!$childItems.Count) -and ($BkKeepEmptyDirs -eq $True) -and !($childItemsScanErrors)) { 1003 | 1004 | # Older versions of 7zip require at least one file to save a folder 1005 | # Newer versions will simply create the folder 1006 | If ([int]$MyContext.SevenZBinVersionInfo.Major -le 9) { 1007 | # Try to drop a placeholder file and reload child items 1008 | $childFile = New-Item (Join-Path -Path $thisFolder.RelativeName -ChildPath $MyContext.DummyFile) -type File 1009 | If($?) { 1010 | $Counters.PlaceHolders += $childFile 1011 | $SWriters.Inclusions.WriteLine([string](Join-Path -Path $thisFolder.RelativeName -ChildPath $childFile.Name)) 1012 | } 1013 | Return 1014 | } Else { 1015 | $SWriters.Inclusions.WriteLine([string]$thisFolder.RelativeName) 1016 | Return 1017 | } 1018 | 1019 | } 1020 | 1021 | # Process Files Within The Container 1022 | If($scanThisPathForFiles) { 1023 | $childFiles = @($childItems | ? {!$_.PSIsContainer}) 1024 | If($childFiles.Count) { 1025 | for ($i=0; $i -lt $childFiles.Count; $i++) { 1026 | 1027 | $Counters.FilesProcessed++ 1028 | 1029 | $childFile = $childFiles[$i] 1030 | $childFileRealName = Join-Path -Path $thisFolder.RealName -ChildPath $childFile.Name 1031 | 1032 | # >>> Clean up files ? 1033 | If(($matchcleanupfiles) -and ($childFileName -match $matchcleanupfiles)) { 1034 | If(!$BkDryRun) { 1035 | Trace (" Removing F {0} " -f $childFileRealName) 1036 | $childFile | Remove-Item -Force -ErrorVariable childFileRemoveError | Out-Null 1037 | if (!$?) { 1038 | $SWriters.Exceptions.WriteLine([string]("{0}`t{1}`t{2}" -f $Counters.Exceptions++, $childFileRemoveError.CategoryInfo.Reason, $childFileRemoveError.CategoryInfo.TargetName)) 1039 | Trace (" Exception id {0} on {1} " -f $Counters.Exceptions, $childFileRealName) 1040 | continue 1041 | } 1042 | } Else { 1043 | Trace (" Would remove {0} " -f $childFileRealName) 1044 | } 1045 | } 1046 | # <<< 1047 | 1048 | # Archive Attribute : is it set as we need it ? 1049 | If((($BkType -ieq "incr") -or ($BkType -ieq "diff")) -and !($childFile.Attributes -band 32)) { 1050 | continue 1051 | } 1052 | 1053 | # Match Include ? 1054 | If(($matchincludefiles) -and ($childFile.Name -notmatch $matchincludefiles) ) { 1055 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "matchincludefiles", "F", $childFileRealName)) 1056 | continue 1057 | } 1058 | 1059 | # Match Exclude ? 1060 | If(($matchexcludefiles) -and ($childFile.Name -match $matchexcludefiles) ) { 1061 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "matchexcludefiles", "F", $childFileRealName)) 1062 | continue 1063 | } 1064 | 1065 | # Check the file falls into MaxFileAge 1066 | If(($BkMaxFileAge) -and ((New-Timespan $childFile.LastWriteTime $MyContext.SelectionStart).TotalDays -gt $BkMaxFileAge) ) { 1067 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "maxfileage", "F", $childFileRealName)) 1068 | continue 1069 | } 1070 | 1071 | # Check the file falls into MinFileAge 1072 | If(($BkMinFileAge) -and ((New-Timespan $childFile.LastWriteTime $MyContext.SelectionStart).TotalDays -lt $BkMinFileAge) ) { 1073 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "minfileage", "F", $childFileRealName)) 1074 | continue 1075 | } 1076 | 1077 | # Check the file falls into MaxFileSize 1078 | If(($BkMaxFileSize) -and ($childFile.Length -gt $BkMaxFileSize) ) { 1079 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "maxfilesize", "F", $childFileRealName)) 1080 | continue 1081 | } 1082 | 1083 | # Check the file falls into MinFileSize 1084 | If(($BkMinFileSize) -and ($childFile.Length -lt $BkMinFileSize) ) { 1085 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "minfilesize", "F", $childFileRealName)) 1086 | continue 1087 | } 1088 | 1089 | # Update counters 1090 | $Counters.FilesSelected++ ; 1091 | $Counters.BytesSelected += $childFile.Length ; 1092 | $SWriters.Inclusions.WriteLine([string](Join-Path -Path $thisFolder.RelativeName -ChildPath $childFile.Name)) 1093 | # Save Catalog Stats 1094 | $SWriters.Stats.WriteLine([string]("{0}`t{1}`t{2}" -f $Counters.FilesSelected,$childFile.Extension,$childFile.Length )) 1095 | 1096 | 1097 | } 1098 | } 1099 | } 1100 | 1101 | # Process Directories Within The Container 1102 | If($scanThisPathForRecursion -And (!(Check-CTRLCRequest -eq $True))) { 1103 | $childFolders = @($childItems | ? {$_.PSIsContainer}) 1104 | If($childFolders.Count) { 1105 | for ($i=0; $i -lt $childFolders.Count; $i++) { 1106 | 1107 | $childFolderItem = @{} 1108 | $childFolderItem.Name = $childFolders[$i].Name 1109 | $childFolderItem.FullName = $childFolders[$i].FullName 1110 | $childFolderItem.RelativeName = $childFolders[$i].FullName.Replace($BkRootDir + "\" , "") 1111 | $childFolderItem.ContainerAlias = $thisFolder.ContainerAlias 1112 | $childFolderItem.RealName = Join-Path -Path $BkSources[$thisFolder.ContainerAlias] -ChildPath ($childFolderItem.RelativeName.Replace($thisFolder.ContainerAlias, "")) 1113 | $childFolderItem.Depth = ($thisFolder.Depth + 1); 1114 | 1115 | # Check subdir against recursion in junctions 1116 | If(($BkNoFollowJunctions) -and ($childFolders[$i].Attributes -band 1024)) { 1117 | $SWriters.Exclusions.WriteLine([string]("{0}`t{1}`t{2}`t{3}" -f $Counters.Exclusions++, "nofollowjunctions", "D", $thisFolder.RealName)) 1118 | continue 1119 | } 1120 | 1121 | If ($catalogFoldersIndex -eq $catalogFolders.Count) { 1122 | [void] $catalogFolders.Add($childFolderItem) 1123 | } Else { 1124 | [void] $catalogFolders.Insert(($catalogFoldersIndex + ($i + 1)), $childFolderItem) 1125 | } 1126 | } 1127 | } 1128 | } 1129 | 1130 | } 1131 | 1132 | # ----------------------------------------------------------------------------- 1133 | # Function : Remove-Junction 1134 | # ----------------------------------------------------------------------------- 1135 | # Description : Removes a Junction by the means of SysInternals' Junction.exe 1136 | # Parameters : [string]jPath - Full path to the name of the junction 1137 | # Returns : $True / $False 1138 | # ----------------------------------------------------------------------------- 1139 | Function Remove-Junction { 1140 | param([string]$jPath = $(throw "You must provide a path to the junction")) 1141 | 1142 | # Check Junction Path exist otherwise we have nothing to unJunction 1143 | If((Test-Path $jPath)) { 1144 | 1145 | # UnJunction it 1146 | Invoke-Expression (('& "{0}" /accepteula -d "{1}"') -f $BkJunctionBin, $jPath) 1147 | Start-Sleep --Milliseconds 10 1148 | 1149 | # Test is no more present !! 1150 | Write-Output ((Test-Path -Path $jPath) -eq $False) 1151 | Return 1152 | 1153 | } 1154 | Write-Output $False 1155 | } 1156 | 1157 | # ----------------------------------------------------------------------------- 1158 | # Function : Remove-RootDir 1159 | # ----------------------------------------------------------------------------- 1160 | # Description : This function safely removes the Root Directory generated for 1161 | # the purpouse of holding junction points to included sources. 1162 | # Before it deletes the directory itself, each reparse point 1163 | # is removed using Junction with the -d switch. 1164 | # Parameters : [string]rootPath - The name of the directory to remove 1165 | # Returns : $True / $False 1166 | # ----------------------------------------------------------------------------- 1167 | Function Remove-RootDir { 1168 | param([string]$rootPath = $(throw "You must provide a path to the directory")) 1169 | 1170 | Write-Debug "About to remove root-dir" 1171 | 1172 | If (Test-Path -Path $rootPath -PathType Container) { 1173 | Set-Variable -Name "junctionsRemoved" -Value $True -Scope Private | Out-Null 1174 | Get-ChildItem -Path $rootPath | ? { $_.Attributes -band 1024 } | ForEach-Object { 1175 | If([int]$MyContext.WinVer[0] -lt 6) { 1176 | $junctionsRemoved = Remove-Junction $_.FullName 1177 | If(!$junctionsRemoved) {Return} 1178 | } Else { 1179 | $junctionsRemoved = Remove-SymLink $_.FullName 1180 | If(!$junctionsRemoved) {Return} 1181 | } 1182 | } 1183 | If($junctionsRemoved -And (@(Get-ChildItem -Path $rootPath | ? {$_.PsIsContainer}).Count -eq 0) ) { 1184 | Remove-Item -Path $rootPath -Recurse -Force | Out-Null 1185 | Write-Output $? 1186 | Return 1187 | } 1188 | } 1189 | Write-Output $False 1190 | 1191 | } 1192 | 1193 | # ----------------------------------------------------------------------------- 1194 | # Function : Remove-SymLink 1195 | # ----------------------------------------------------------------------------- 1196 | # Description : Removes a Symbolic Link 1197 | # Parameters : [string]jPath - Full path to the name of the Link 1198 | # Returns : $True / $False 1199 | # ----------------------------------------------------------------------------- 1200 | Function Remove-SymLink { 1201 | param([string]$jPath = $(throw "You must provide a path to the Link")) 1202 | 1203 | # Check Junction Path exist otherwise we have nothing to delete 1204 | If((Test-Path $jPath)) { 1205 | 1206 | # Now we have to check if source contains spaces 1207 | If(($jPath.Contains(" "))) { $jPath = """$jPath""" } 1208 | 1209 | # Remove the Link 1210 | cmd /c ("RD `"{0}`"" -f $jPath) 1211 | Start-Sleep -Milliseconds 10 1212 | 1213 | # Test is no more present !! 1214 | Write-Output ((Test-Path -Path $jPath) -eq $False) 1215 | Return 1216 | 1217 | } 1218 | Write-Output $False 1219 | } 1220 | 1221 | # ----------------------------------------------------------------------------- 1222 | # Function : Send-Notification 1223 | # ----------------------------------------------------------------------------- 1224 | # Description : Sends the notification email to given adressee 1225 | # Parameters : None 1226 | # Returns : $True / $False 1227 | # ----------------------------------------------------------------------------- 1228 | Function Send-Notification { 1229 | 1230 | Try { 1231 | [console]::TreatControlCAsInput = $True 1232 | } Catch {} 1233 | 1234 | # Ensure file stream writers are closed 1235 | $SWriters.GetEnumerator() | ForEach-Object { 1236 | Try { 1237 | $_.Value.Flush() 1238 | $_.Value.Close() 1239 | $_.Value.Dispose() 1240 | } Catch {} 1241 | } 1242 | 1243 | # Do nothing if we have no-one to notify 1244 | # Or we do not have enough info to issue the email 1245 | If(!($BkNotifyLog)) { return; } 1246 | If(!($BkSmtpFrom)) { return; } 1247 | If(!($BkSmtpRelay)) { return; } 1248 | If(!($BkSmtpPort)) { return; } 1249 | 1250 | Write-Host "`n Sending notification email ..." 1251 | 1252 | $SmtpClient = [Object] 1253 | $MailMessage = [Object] 1254 | 1255 | Try { 1256 | 1257 | If(!(Test-Variable "BkMailSubject")) { Set-Variable -name "BkMailSubject" -value ("7zBackup Report Host $Env:ComputerName") -scope Script } 1258 | $SmtpClient = New-Object system.net.mail.smtpClient 1259 | $MailMessage = New-Object system.net.mail.mailmessage 1260 | 1261 | $SmtpClient.Host = $BkSmtpRelay 1262 | $SmtpClient.Port = $BkSmtpPort 1263 | $SmtpClient.EnableSsl = ($BkSmtpSSL) 1264 | 1265 | # If we have both smtpuser and smtppass then we need to authenticate 1266 | if ((Test-Variable "BkSmtpUser") -and (Test-Variable "BkSmtpPass")) { 1267 | $SmtpUserInfo = New-Object System.Net.NetworkCredential($BkSmtpUser, $BkSmtpPass) 1268 | $SmtpClient.UseDefaultCredentials = $False 1269 | $SmtpClient.Credentials = $SmtpUserInfo 1270 | } 1271 | 1272 | If(($Counters.Warnings -gt 0)) { $MailMessage.Priority = [System.Net.Mail.MailPriority]::High } 1273 | If(($Counters.Criticals -gt 0)) { $MailMessage.Priority = [System.Net.Mail.MailPriority]::High; $BkMailSubject = "Critical ! $BkMailSubject" } 1274 | $MailMessage.From = $BkSmtpFrom 1275 | 1276 | If(($BkNotifyLog -is [array])) { 1277 | For ($x=0; $x -lt $BkNotifyLog.Length; $x++) { $MailMessage.To.Add($BkNotifyLog[$x]) } 1278 | } Else { 1279 | $MailMessage.To.Add($BkNotifyLog) 1280 | } 1281 | 1282 | If($BkNotifyLogCc) { 1283 | If(($BkNotifyLogCc -is [array])) { 1284 | For ($x=0; $x -lt $BkNotifyLogCc.Length; $x++) { $MailMessage.Cc.Add($BkNotifyLogCc[$x]) } 1285 | } Else { 1286 | $MailMessage.Cc.Add($BkNotifyLogCc) 1287 | } 1288 | } 1289 | 1290 | If($BkNotifyLogBcc) { 1291 | If(($BkNotifyLogBcc -is [array])) { 1292 | For ($x=0; $x -lt $BkNotifyLogBcc.Length; $x++) { $MailMessage.Bcc.Add($BkNotifyLogBcc[$x]) } 1293 | } Else { 1294 | $MailMessage.Bcc.Add($BkNotifyLogBcc) 1295 | } 1296 | } 1297 | 1298 | $MailMessage.Subject = $BkMailSubject 1299 | $MailMessage.Body = ($MyContext.Logger.ToString()) 1300 | 1301 | # Do we have to include extra informations ? 1302 | If ($BkNotifyExtra -ne "none") { 1303 | 1304 | Get-ChildItem -Path $BkRootDir -Force | ? {!$_.PSIsContainer} | ForEach-Object { 1305 | If( 1306 | ($_.Length -gt 0) -And 1307 | ($_.Name -notmatch "stats") -And 1308 | ($_.Name -notmatch "README") 1309 | ) { 1310 | If($BkNotifyExtra -ieq "attach") { 1311 | $MailAttachment = New-Object System.Net.Mail.Attachment($_.FullName) 1312 | $MailAttachment.Name = $_.Name 1313 | $MailMessage.Attachments.Add($MailAttachment) 1314 | } Else { 1315 | $MailMessage.Body += ("`n`n{0}`n" -f $_.Name) 1316 | $MailMessage.Body += (Get-Content $_) 1317 | } 1318 | } 1319 | } 1320 | 1321 | } 1322 | 1323 | [void] $SmtpClient.Send($MailMessage) 1324 | Write-Host " Done`n " -ForeGroundColor Green 1325 | 1326 | } 1327 | 1328 | Catch { 1329 | Write-Host (" Unable to send notification email : {0} `n " -f $_.Exception.Categoryinfo.Reason ) -ForeGroundColor Red 1330 | } 1331 | 1332 | Finally { 1333 | If ($MailMessage.GetType().Name -ieq "MailMessage") { $MailMessage.Dispose() } 1334 | } 1335 | 1336 | } 1337 | 1338 | # ----------------------------------------------------------------------------- 1339 | # Function : Test-Lock 1340 | # ----------------------------------------------------------------------------- 1341 | # Description : This function is used to check if a previous lock file exists 1342 | # Returns : [] 1343 | # ----------------------------------------------------------------------------- 1344 | Function Test-Lock { 1345 | 1346 | If(Test-Path -LiteralPath $BkLockFile -pathType Leaf) { 1347 | 1348 | # A previously executed script has left it's lock file 1349 | Get-Content $BkLockFile -Encoding Ascii | Where-Object {$_ -imatch "^PID="} | ForEach-Object { 1350 | If($_ -match "^PID=") {Set-Variable -name "OldPid" -value ($_.Substring($_.IndexOf("=") + 1)) -scope Local } 1351 | If($_ -match "^Root=") {Set-Variable -name "OldRoot" -value ($_.Substring($_.IndexOf("=") + 1)) -scope Local } 1352 | } 1353 | 1354 | If (Test-Variable "OldPid") { 1355 | 1356 | $OldProcess = Get-Process -Id $OldPid 1357 | If (($?) -And ($OldProcess)) { 1358 | 1359 | If ($OldPid -eq [System.Diagnostics.Process]::GetCurrentProcess().Id) { 1360 | 1361 | If ((Test-Variable "OldRoot")) { 1362 | If(Test-Path $OldRoot -PathType Container ) { Remove-RootDir $OldRoot | Out-Null} 1363 | } 1364 | Remove-Item -LiteralPath $BkLockFile -Force | Out-Null 1365 | 1366 | } 1367 | 1368 | ElseIf ($OldProcess.Responding) { 1369 | 1370 | Write-Output ("A previous operation is running with process id {0}`n Quitting ...`n " -f $OldPid) 1371 | Return 1372 | } 1373 | 1374 | Else { 1375 | 1376 | # Try Stopping the non-responding process 1377 | Stop-Process -Id $OldPid -Force | Out-Null 1378 | If(!($?)) { 1379 | Write-Output ("A previous operation is not responding with process id {0}`n Quitting ...`n " -f $OldPid) 1380 | Return 1381 | } 1382 | If(Test-Variable "OldRoot") { If(Test-Path -LiteralPath $OldRoot -PathType Container ) { Remove-RootDir $OldRoot | Out-Null } } 1383 | Remove-Item -LiteralPath $BkLockFile | Out-Null 1384 | If(!($?)) { 1385 | Write-Output ("Could not remove a previous lock file`n Quitting ...`n ") 1386 | Return 1387 | } 1388 | 1389 | } 1390 | 1391 | } 1392 | 1393 | 1394 | 1395 | } Else { 1396 | 1397 | If ((New-TimeSpan -End (Get-Date) -Start (Get-Item -LiteralPath $BkLockFile).LastWriteTime).TotalHours -gt 72) { 1398 | 1399 | Remove-Item -LiteralPath $BkLockFile | Out-Null 1400 | If(!($?)) { 1401 | Write-Output ("Could not remove a previous lock file") 1402 | Write-Output ("Check lock file {0}" -f $BkLockFile ) 1403 | Write-Output ("Quitting ...") 1404 | Return 1405 | } 1406 | 1407 | } Else { 1408 | 1409 | Write-Output ("A previous operation is running or has stopped abnormally") 1410 | Write-Output ("Check lock file {0}" -f $BkLockFile ) 1411 | Write-Output ("Quitting ...") 1412 | return 1413 | 1414 | } 1415 | } 1416 | 1417 | } 1418 | 1419 | # Drop a new lock file in place 1420 | New-Item -Path $BkLockFile -ItemType File -Force | Out-Null 1421 | If ($?) {("PID={0}`nRoot={1}" -f [System.Diagnostics.Process]::GetCurrentProcess().Id, $BkRootDir) | Out-File $BkLockFile -encoding ASCII -append } 1422 | If(!($?)) { 1423 | Write-Output ("Could not write lock file`n Quitting ...`n ") 1424 | Return 1425 | } 1426 | 1427 | } 1428 | 1429 | # ----------------------------------------------------------------------------- 1430 | # Function : Test-Path-Writable 1431 | # ----------------------------------------------------------------------------- 1432 | # Description : Checks a given path is writable 1433 | # Parameters : [string]targetPath - Full path to the directory to test 1434 | # Returns : $True / $False 1435 | # ----------------------------------------------------------------------------- 1436 | Function Test-Path-Writable { 1437 | param([string]$testPath = $(throw "You must provide a path to test"), 1438 | [string]$testType = $(throw "You must provide a test item type")) 1439 | 1440 | # Check Path Exist 1441 | If(Test-Path -Path $testPath -PathType Container) { 1442 | 1443 | # Generate a dummy file name with a Guid 1444 | $dummyItem = Join-Path $testPath ( [System.Guid]::NewGuid().ToString() ) 1445 | 1446 | # Try to create new file in tested path 1447 | if (( $testType -ieq "file" )) { 1448 | New-Item $dummyItem -type File -force -value "This is only a test file. You can delete it safely." | Out-Null 1449 | } Else { 1450 | New-Item $dummyItem -type Directory -force | Out-Null 1451 | } 1452 | If ($?) { 1453 | Remove-Item $dummyItem | Out-Null 1454 | Write-Output $? 1455 | Return 1456 | } Else { 1457 | Write-Output $? 1458 | Return 1459 | } 1460 | 1461 | } 1462 | Write-Output $False 1463 | } 1464 | 1465 | # ----------------------------------------------------------------------------- 1466 | # Function : Test-Variable 1467 | # ----------------------------------------------------------------------------- 1468 | # Description : This function is used to check if a variables name exist 1469 | # in the Variables scope 1470 | # Parameters : [string]varName - The name of the Variable to test for 1471 | # Returns : $True / $False 1472 | # ----------------------------------------------------------------------------- 1473 | Function Test-Variable { 1474 | param([string]$varName = $(throw "You must provide a variable name")) 1475 | Get-Variable -name $varName -scope Script | Out-Null 1476 | Write-Output $? 1477 | } 1478 | 1479 | # ----------------------------------------------------------------------------- 1480 | # Function : Trace 1481 | # ----------------------------------------------------------------------------- 1482 | # Description : Outputs message to console and to logfile 1483 | # Parameters : [string]$message - The message to output 1484 | # Returns : -- 1485 | # ----------------------------------------------------------------------------- 1486 | Function Trace ($message) { 1487 | Write-Host ($message) 1488 | [void]$MyContext.Logger.AppendLine($message) 1489 | } 1490 | 1491 | # ----------------------------------------------------------------------------- 1492 | # Function : Pause 1493 | # ----------------------------------------------------------------------------- 1494 | # Description : Outputs message to console and waits for any key 1495 | # Parameters : [string]$message - The message to output 1496 | # Returns : -- 1497 | # ----------------------------------------------------------------------------- 1498 | Function Pause ($Message="`n Paused. Press any key to continue...`r") { 1499 | Write-Host -NoNewLine $Message 1500 | $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | Out-Null 1501 | Write-Host " " 1502 | } 1503 | 1504 | # ----------------------------------------------------------------------------- 1505 | # Function : Validate-Arguments 1506 | # ----------------------------------------------------------------------------- 1507 | # Description : This function is used to check input arguments 1508 | # Parameters : None 1509 | # Returns : An array of error messages (if any) 1510 | # ----------------------------------------------------------------------------- 1511 | Function Validate-Arguments { 1512 | 1513 | If($BkArguments.length -ne 0) { 1514 | $i = 0 1515 | do { 1516 | switch ($BkArguments[$i]) { 1517 | "--type" { Set-Variable -name BkType -value $BkArguments[++$i] -scope Script } 1518 | "--workdir" { Set-Variable -name BkWorkDir -value $BkArguments[++$i] -scope Script } 1519 | "--workdrive" { Set-Variable -name BkWorkDrive -value $BkArguments[++$i] -scope Script } 1520 | "--selection" { Set-Variable -name BkSelection -value $BkArguments[++$i] -scope Script } 1521 | "--destpath" { Set-Variable -name BkDestPath -value $BkArguments[++$i] -scope Script } 1522 | "--archiveprefix" { Set-Variable -name BkArchivePrefix -value $BkArguments[++$i] -scope Script } 1523 | "--prefix" { Set-Variable -name BkArchivePrefix -value $BkArguments[++$i] -scope Script } 1524 | "--archivetype" { Set-Variable -name BkArchiveType -value $BkArguments[++$i] -scope Script } 1525 | "--compression" { Set-Variable -name BkArchiveCompression -value $BkArguments[++$i] -scope Script } 1526 | "--threads" { Set-Variable -name BkArchiveThreads -value $BkArguments[++$i] -scope Script } 1527 | "--solid" { Set-Variable -name BkArchiveSolid -value $BkArguments[++$i] -scope Script } 1528 | "--volumes" { Set-Variable -name BkArchiveVolumes -value $BkArguments[++$i] -scope Script } 1529 | "--archivepassword" { Set-Variable -name BkArchivePassword -value $BkArguments[++$i] -scope Script } 1530 | "--password" { Set-Variable -name BkArchivePassword -value $BkArguments[++$i] -scope Script } 1531 | "--encryptheaders" { Set-Variable -name BkEncryptHeaders -value $True -scope Script } 1532 | "--rotate" { Set-Variable -name BkRotate -value $BkArguments[++$i] -scope Script } 1533 | "--emptydirs" { Set-Variable -name BkKeepEmptyDirs -value $True -scope Script } 1534 | "--maxdepth" { Set-Variable -name BkMaxDepth -value $BkArguments[++$i] -scope Script } 1535 | "--maxfileage" { Set-Variable -name BkMaxFileAge -value $BkArguments[++$i] -scope Script } 1536 | "--minfileage" { Set-Variable -name BkMinFileAge -value $BkArguments[++$i] -scope Script } 1537 | "--maxfilesize" { Set-Variable -name BkMaxFileSize -value $BkArguments[++$i] -scope Script } 1538 | "--minfilesize" { Set-Variable -name BkMinFileSize -value $BkArguments[++$i] -scope Script } 1539 | "--clearbit" { Set-Variable -name BkClearBit -value $BkArguments[++$i] -scope Script } 1540 | "--logfile" { Set-Variable -name BkLogFile -value $BkArguments[++$i] -scope Script ; Remove-Variable -name BkLogFile -scope Script } 1541 | "--notify" { Set-Variable -name BkNotifyLog -value $BkArguments[++$i] -scope Script } 1542 | "--notifyto" { Set-Variable -name BkNotifyLog -value $BkArguments[++$i] -scope Script } 1543 | "--notifytoCc" { Set-Variable -name BkNotifyLogCc -value $BkArguments[++$i] -scope Script } 1544 | "--notifytoBcc" { Set-Variable -name BkNotifyLogBcc -value $BkArguments[++$i] -scope Script } 1545 | "--notifyfrom" { Set-Variable -name BkSmtpFrom -value $BkArguments[++$i] -scope Script } 1546 | "--notifyextra" { Set-Variable -name BkNotifyExtra -value $BkArguments[++$i] -scope Script } 1547 | "--smtpserver" { Set-Variable -name BkSmtpRelay -value $BkArguments[++$i] -scope Script } 1548 | "--smtpport" { Set-Variable -name BkSmtpPort -value $BkArguments[++$i] -scope Script } 1549 | "--smtpuser" { Set-Variable -name BkSmtpUser -value $BkArguments[++$i] -scope Script } 1550 | "--smtppass" { Set-Variable -name BkSmtpPass -value $BkArguments[++$i] -scope Script } 1551 | "--smtpssl" { Set-Variable -name BkSmtpSSL -value $True -scope Script } 1552 | "--7zbin" { Set-Variable -name Bk7ZipBin -value $BkArguments[++$i] -scope Script } 1553 | "--7zipbin" { Set-Variable -name Bk7ZipBin -value $BkArguments[++$i] -scope Script } 1554 | "--jbin" { Set-Variable -name BkJunctionBin -value $BkArguments[++$i] -scope Script } 1555 | "--dry" { Set-Variable -name BkDryRun -value $True -scope Script } 1556 | "--pre" { Set-Variable -name BkPreAction -value $BkArguments[++$i] -scope Script } 1557 | "--post" { Set-Variable -name BkPostAction -value $BkArguments[++$i] -scope Script } 1558 | 1559 | Default { Write-Output ("Unknown argument {0}" -f $BkArguments[$i]) } 1560 | } 1561 | $i++ 1562 | } 1563 | while ($i -lt $BkArguments.length) 1564 | } 1565 | } 1566 | 1567 | # ----------------------------------------------------------------------------- 1568 | # Function : Validate-Variables 1569 | # ----------------------------------------------------------------------------- 1570 | # Description : This function is used to check variables needed to execute 1571 | # the script. 1572 | # Parameters : None 1573 | # Returns : An array of error messages (if any) 1574 | # ----------------------------------------------------------------------------- 1575 | Function Validate-Variables { 1576 | 1577 | # -------------------------------------------------------------------------------------------------------------------------- 1578 | # Environment - Checks 1579 | # -------------------------------------------------------------------------------------------------------------------------- 1580 | # Check we're on Powershell 3.x. If not early exit. 1581 | If($MyContext.PSVer -lt 2) { 1582 | Write-Output ("You must be on PowerShell 2.x (or better) to run this script. You're on {0}" -f $MyContext.PSVer) 1583 | Return 1584 | } 1585 | 1586 | # -------------------------------------------------------------------------------------------------------------------------- 1587 | # Clear Archive Bit Policy - Checks 1588 | # -------------------------------------------------------------------------------------------------------------------------- 1589 | If((Test-Variable "BkClearBit") -eq $True) { 1590 | Set-Variable -name b -value $True -scope Local 1591 | If([system.boolean]::tryparse($BkClearBit,[ref]$b)) { 1592 | Set-Variable -name BkClearBit -value $b -scope Script 1593 | } Else { 1594 | Write-Output "Value $BkClearBit for --clearbit argument is not valid boolean value." 1595 | Remove-Variable -name BkClearBit -scope Script 1596 | } 1597 | Remove-Variable -name b -scope Local 1598 | } 1599 | 1600 | # -------------------------------------------------------------------------------------------------------------------------- 1601 | # Backup Type - Checks 1602 | # -------------------------------------------------------------------------------------------------------------------------- 1603 | If(!(Test-Variable "BkType")) { 1604 | Write-Output "Missing or invalid --type argument" 1605 | } Else { 1606 | Switch ($BkType) { 1607 | "full" { $BkType = "full"; If(!(Test-Variable "BkClearBit")) { Set-Variable -name BkClearBit -value $True -scope Script } } 1608 | "incr" { $BkType = "incr"; If(!(Test-Variable "BkClearBit")) { Set-Variable -name BkClearBit -value $True -scope Script } } 1609 | "diff" { $BkType = "diff"; If(!(Test-Variable "BkClearBit")) { Set-Variable -name BkClearBit -value $False -scope Script } } 1610 | "copy" { $BkType = "copy"; If(!(Test-Variable "BkClearBit")) { Set-Variable -name BkClearBit -value $False -scope Script } } 1611 | "move" { $BkType = "move"; If(!(Test-Variable "BkClearBit")) { Set-Variable -name BkClearBit -value $False -scope Script } } 1612 | Default { Write-Output "Missing or invalid --type argument" } 1613 | } 1614 | } 1615 | 1616 | # -------------------------------------------------------------------------------------------------------------------------- 1617 | # Work drive - Checks 1618 | # -------------------------------------------------------------------------------------------------------------------------- 1619 | # If missing or set to "auto" we will assume drive letter for TEMP path. 1620 | # If passed from command line arguments we have to check is a valid drive letter 1621 | # and path is writable and, of course, is NTFS filesystem 1622 | If(!(Test-Variable "BkWorkDrive")) { Set-Variable -name BkWorkDrive -value "auto" -scope Script } 1623 | If($BkWorkDrive -ieq "auto") { Set-Variable -name BkWorkDrive -value ($Env:Temp).Substring(0,1) -scope Script } 1624 | If ( 1625 | ($BkWorkDrive -ieq "") -or 1626 | ($BkWorkDrive -is [array]) -or 1627 | ($BkWorkDrive -notmatch "^[C-Z]{1}$") -or 1628 | (Test-Path ($BkWorkDrive + ":\") -eq $False) -or 1629 | ((Test-Path-Writable ($BkWorkDrive + ":\") "Directory") -eq $False) -or 1630 | ((New-Object System.Io.DriveInfo($BkWorkDrive)).DriveFormat -ieq "NTFS") 1631 | ) { Write-Output "Missing or invalid --workdrive argument. Must be writable NTFS drive" } 1632 | 1633 | # -------------------------------------------------------------------------------------------------------------------------- 1634 | # Selection file - Checks 1635 | # -------------------------------------------------------------------------------------------------------------------------- 1636 | If ( 1637 | ((Test-Variable "BkSelection") -eq $False) -or 1638 | ($BkSelection -match "^\s*$") -or 1639 | ((Test-Path $BkSelection -pathType Leaf) -eq $False) -or 1640 | (Check-FsAttribute $BkSelection "Directory") 1641 | ) { Write-Output "Missing or invalid --selection argument. Must be an existent file" } 1642 | Else 1643 | { 1644 | 1645 | # Resolve full name to file 1646 | Set-Variable -name BkSelection -value ((Get-Item $BkSelection).FullName) -Scope Script 1647 | 1648 | # Try to load Selection Directives (if any) 1649 | # Load all rows except comments and empty lines. 1650 | Remove-Variable -name BkSelectionContents -scope Script 1651 | Set-Variable -name BkSelectionContents -scope Script -Value @(Get-Content $BkSelection | ? {$_ -notmatch "^#|^\s*$"}) 1652 | 1653 | # If we have no directive from selection then handle the error 1654 | If( 1655 | ((Test-Variable "BkSelectionContents") -eq $False) -Or 1656 | ($BkSelectionContents.Count -eq 0) -Or 1657 | !(($BkSelectionContents | Where-Object {$_ -match "^includesource=*"}).Length -gt 0) 1658 | ) { Write-Output "Missing or invalid --selection argument: file does not contain any `"includesource`" directive" } 1659 | Else 1660 | { 1661 | 1662 | # Look whether selection contents holds specific 7zip switches to use. (REMOVED) 1663 | #$BkSelectionContents | Where-Object {$_ -match "^useswitches=*"} | ForEach-Object { Set-Variable -name "Bk7ZipSwitches" -value ($_.Substring($_.IndexOf("=") + 1)) -scope Script } 1664 | 1665 | # Look whether selection contents holds specific maxdepth value to use. 1666 | $BkSelectionContents | Where-Object {$_ -match "^maxdepth=[0-9]"} | ForEach-Object { Set-Variable -name "BkMaxDepth" -value ($_.Substring($_.IndexOf("=") + 1)) -scope Script } 1667 | 1668 | # Look whether selection contents holds specific rotate value to use. 1669 | $BkSelectionContents | Where-Object {$_ -match "^rotate=[0-9]"} | ForEach-Object { Set-Variable -name "BkRotate" -value ($_.Substring($_.IndexOf("=") + 1)) -scope Script } 1670 | 1671 | # Look whether selection contents holds specific prefix value to use. 1672 | $BkSelectionContents | Where-Object {$_ -match "^prefix=*"} | ForEach-Object { Set-Variable -name "BkArchivePrefix" -value ($_.Substring($_.IndexOf("=") + 1)) -scope Script } 1673 | 1674 | # Look whether selection contents sets the keeping of empty dirs. 1675 | $BkSelectionContents | Where-Object {$_ -match "^emptydirs$"} | ForEach-Object { Set-Variable -name "BkKeepEmptyDirs" -value $True -scope Script } 1676 | 1677 | # Look whether selection contents sets following of junctions 1678 | $BkSelectionContents | Where-Object {$_ -match "^nofollowjunctions$"} | ForEach-Object { Set-Variable -name "BkNoFollowJunctions" -value $True -scope Script } 1679 | 1680 | # Look whether selection contents sets max/min file sizes 1681 | $BkSelectionContents | ? {$_ -match "^maxfilesize=\d+"} | select @{Name="Value";Expression={$_.Substring($_.IndexOf("=") + 1).Replace(",",".")}} | ForEach-Object {Set-Variable -Name "BkMaxFileSize" -Value $_.Value} 1682 | $BkSelectionContents | ? {$_ -match "^minfilesize=\d+"} | select @{Name="Value";Expression={$_.Substring($_.IndexOf("=") + 1).Replace(",",".")}} | ForEach-Object {Set-Variable -Name "BkMinFileSize" -Value $_.Value} 1683 | 1684 | # Look whether selection contents sets max/min file ages 1685 | $BkSelectionContents | ? {$_ -match "^maxfileage=\d+(\,|\.)\d+"} | select @{Name="Value";Expression={$_.Substring($_.IndexOf("=") + 1).Replace(",",".")}} | ForEach-Object {Set-Variable -Name "BkMaxFileAge" -Value $_.Value} 1686 | $BkSelectionContents | ? {$_ -match "^minfileage=\d+(\,|\.)\d+"} | select @{Name="Value";Expression={$_.Substring($_.IndexOf("=") + 1).Replace(",",".")}} | ForEach-Object {Set-Variable -Name "BkMinFileAge" -Value $_.Value} 1687 | 1688 | # Look for compression 1689 | $BkArchiveCompression | ? {$_ -match "^compression=\d+"} | select @{Name="Value";Expression={$_.Substring($_.IndexOf("=") + 1).Replace(",",".")}} | ForEach-Object {Set-Variable -Name "BkArchiveCompression" -Value $_.Value} 1690 | 1691 | # Look for threads 1692 | $BkArchiveThreads | ? {$_ -match "^threads=\d+"} | select @{Name="Value";Expression={$_.Substring($_.IndexOf("=") + 1).Replace(",",".")}} | ForEach-Object {Set-Variable -Name "BkArchiveThreads" -Value $_.Value} 1693 | 1694 | # Look for Solid mode 1695 | $BkArchiveSolid | ? {$_ -match "^solid=\d+"} | select @{Name="Value";Expression={$_.Substring($_.IndexOf("=") + 1).Replace(",",".")}} | ForEach-Object {Set-Variable -Name "BkArchiveSolid" -Value $_.Value} 1696 | 1697 | } 1698 | } 1699 | 1700 | # -------------------------------------------------------------------------------------------------------------------------- 1701 | # Directives - Checks 1702 | # -------------------------------------------------------------------------------------------------------------------------- 1703 | 1704 | If (Test-Variable "BkMaxFileSize") { 1705 | Set-Variable -Name "i" -Value [int64]0 -Scope Local 1706 | If(([system.int64]::tryparse($BkMaxFileSize, [System.Globalization.NumberStyles]::Number, [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US") ,[ref]$d))) { 1707 | Set-Variable -Name "BkMaxFileSize" -Value ([Math]::Abs($d)) -Scope Script 1708 | } Else { 1709 | Write-Output "Missing or invalid maxfilesize directive. Must be an integer" 1710 | } 1711 | Remove-Variable -Name "i" 1712 | } 1713 | If (Test-Variable "BkMinFileSize") { 1714 | Set-Variable -Name "i" -Value [int64]0 -Scope Local 1715 | If(([system.int64]::tryparse($BkMinFileSize, [System.Globalization.NumberStyles]::Number, [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US") ,[ref]$i))) { 1716 | Set-Variable -Name "BkMinFileSize" -Value ([Math]::Abs($i)) -Scope Script 1717 | } Else { 1718 | Write-Output "Missing or invalid minfilesize directive. Must be an integer" 1719 | } 1720 | Remove-Variable -Name "i" 1721 | } 1722 | If((Test-Variable "BkMaxFileSize") -And !($BkMaxFileSize -gt 0)) { Remove-Variable -Name "BkMaxFileSize" } 1723 | If((Test-Variable "BkMinFileSize") -And !($BkMinFileSize -gt 0)) { Remove-Variable -Name "BkMinFileSize" } 1724 | 1725 | If (Test-Variable "BkMaxFileAge") { 1726 | Set-Variable -Name "d" -Value [double]0 -Scope Local 1727 | If(([system.Double]::tryparse($BkMaxFileAge, [System.Globalization.NumberStyles]::AllowDecimalPoint, [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US") ,[ref]$d))) { 1728 | Set-Variable -Name "BkMaxFileAge" -Value ([Math]::Abs($d)) -Scope Script 1729 | } Else { 1730 | Write-Output "Missing or invalid minfilesize directive. Must be a valid number" 1731 | } 1732 | Remove-Variable -Name "d" 1733 | } 1734 | 1735 | If (Test-Variable "BkMinFileAge") { 1736 | Set-Variable -Name "d" -Value [double]0 -Scope Local 1737 | If(([system.Double]::tryparse($BkMinFileAge, [System.Globalization.NumberStyles]::AllowDecimalPoint, [System.Globalization.CultureInfo]::CreateSpecificCulture("en-US") ,[ref]$d))) { 1738 | Set-Variable -Name "BkMinFileAge" -Value ([Math]::Abs($d)) -Scope Script 1739 | } Else { 1740 | Write-Output "Missing or invalid minfilesize directive. Must be a valid number" 1741 | } 1742 | Remove-Variable -Name "d" 1743 | } 1744 | 1745 | If((Test-Variable "BkMaxFileAge") -And !($BkMaxFileAge -gt 0)) { Remove-Variable -Name "BkMaxFileAge" } 1746 | If((Test-Variable "BkMinFileAge") -And !($BkMinFileAge -gt 0)) { Remove-Variable -Name "BkMinFileAge" } 1747 | 1748 | 1749 | # -------------------------------------------------------------------------------------------------------------------------- 1750 | # Destination Path - Checks 1751 | # -------------------------------------------------------------------------------------------------------------------------- 1752 | # Destination path given and existent 1753 | If( 1754 | !($BkDestPath) -Or 1755 | ($BkDestPath -match "^\s*$") -Or 1756 | !(Test-Path $BkDestPath -pathType Container) -Or 1757 | !(Check-FsAttribute $BkDestPath "Directory") -Or 1758 | !(Test-Path-Writable $BkDestPath "File") 1759 | ) { 1760 | Write-Output ("Missing or invalid --destpath {0}." -f $BkDestPath) 1761 | Write-Output ("Ensure above path is reachable and writable") 1762 | } 1763 | 1764 | # -------------------------------------------------------------------------------------------------------------------------- 1765 | # Archive Prefix - Checks 1766 | # -------------------------------------------------------------------------------------------------------------------------- 1767 | # Check Archive Prefix does not contain unallowed chars 1768 | If( 1769 | !(Test-Variable "BkArchivePrefix") -Or 1770 | ($BkArchivePrefix -match "^\s*$") -Or 1771 | !(Test-Path -Path $BkArchivePrefix -IsValid) 1772 | ) { Write-Output "Missing or invalid --prefix argument" } 1773 | 1774 | # -------------------------------------------------------------------------------------------------------------------------- 1775 | # Archive Type - Checks 1776 | # -------------------------------------------------------------------------------------------------------------------------- 1777 | If(!(Test-Variable "BkArchiveType")) { 1778 | Set-Variable -name BkArchiveType -value "7z" -scope Script 1779 | } Else { 1780 | Switch ($BkArchiveType) { 1781 | "7z" { Set-Variable -name BkArchiveType -value "7z" -scope Script } 1782 | "zip" { Set-Variable -name BkArchiveType -value "zip" -scope Script } 1783 | "tar" { Set-Variable -name BkArchiveType -value "tar" -scope Script } 1784 | Default { Write-Output "Missing or invalid --archivetype argument" } 1785 | } 1786 | } 1787 | 1788 | # -------------------------------------------------------------------------------------------------------------------------- 1789 | # Archive Compression - Checks 1790 | # -------------------------------------------------------------------------------------------------------------------------- 1791 | If(Test-Variable "BkArchiveCompression") { 1792 | If ($BkArchiveCompression -notmatch "^0$|^1$|^3$|^5$|^7$|^9$") { 1793 | Write-Output "Missing or invalid --compression argument" 1794 | } Else { 1795 | Set-Variable -Name BkArchiveCompression -Value ([int]$BkArchiveCompression) -Scope Script 1796 | } 1797 | } 1798 | 1799 | # -------------------------------------------------------------------------------------------------------------------------- 1800 | # Solid archive policy - Checks 1801 | # -------------------------------------------------------------------------------------------------------------------------- 1802 | If((Test-Variable "BkArchiveSolid") -eq $True) { 1803 | Set-Variable -name b -value $True -scope Local 1804 | If([system.boolean]::tryparse($BkArchiveSolid,[ref]$b)) { 1805 | Set-Variable -name BkArchiveSolid -value $b -scope Script 1806 | } Else { 1807 | Write-Output "Provided value for --solid argument is not valid boolean value." 1808 | Remove-Variable -name BkArchiveSolid -scope Script 1809 | } 1810 | Remove-Variable -name b -scope Local 1811 | } Else { 1812 | Set-Variable -name "BkArchiveSolid" -value $True -scope Script 1813 | } 1814 | 1815 | # -------------------------------------------------------------------------------------------------------------------------- 1816 | # Volumes archive policy - Checks 1817 | # -------------------------------------------------------------------------------------------------------------------------- 1818 | If((Test-Variable "BkArchiveVolumes") -eq $True) { 1819 | If(!($BkArchiveVolumes -is [array])) { $BkArchiveVolumes = @($BkArchiveVolumes) } 1820 | $BkArchiveVolumes | ForEach-Object { If($_ -notmatch "\d+[b|k|m|g]") { Write-Output ("Missing or invalid --volumes argument {0} " -f $_) } } 1821 | } 1822 | 1823 | # -------------------------------------------------------------------------------------------------------------------------- 1824 | # Threading - Checks 1825 | # -------------------------------------------------------------------------------------------------------------------------- 1826 | If(Test-Variable "BkArchiveThreads") { 1827 | If ($BkArchiveThreads -notmatch "^\d*$") { 1828 | Write-Output "Missing or invalid --threads argument" 1829 | } Else { 1830 | Set-Variable -Name "BkArchiveThreads" -Value ([int]$BkArchiveThreads) -Scope Script 1831 | Set-Variable -Name "tmpNumCores" -Value([int]0) -Scope Local 1832 | 1833 | # Check number of threads does not exceed number of available (logical) cores 1834 | Get-WmiObject -class win32_processor | ForEach-Object { 1835 | If($_.NumberOfLogicalProcessors) { 1836 | $tmpNumCores += [int]$_.NumberOfLogicalProcessors 1837 | } 1838 | ElseIf($_.NumberOfCores) { 1839 | $tmpNumCores += [int]$_.NumberOfCores 1840 | } 1841 | Else { 1842 | $tmpNumCores ++ 1843 | } 1844 | } 1845 | If($BkArchiveThreads -gt $tmpNumCores) { 1846 | Write-Output ("Missing or invalid --threads [{0}] argument. Must not exceed {1}" -f $BkArchiveThreads, $tmpNumCores) 1847 | } 1848 | Remove-Variable -Name "tmpNumCores" 1849 | } 1850 | } 1851 | 1852 | 1853 | # -------------------------------------------------------------------------------------------------------------------------- 1854 | # Archive Rotation Policy - Checks 1855 | # -------------------------------------------------------------------------------------------------------------------------- 1856 | If((Test-Variable "BkRotate")) { 1857 | Set-Variable -name i -value ([int]0) -scope Local 1858 | If(([system.int64]::tryparse($BkRotate,[ref]$i))) { 1859 | Set-Variable -name BkRotate -value $i -scope Script 1860 | If(!($BkRotate -gt 0)) { 1861 | Write-Output "Missing or invalid --rotate argument. Must be positive integer" 1862 | Remove-Variable -name BkRotate -scope Script 1863 | } 1864 | } Else { 1865 | Write-Output "Missing or invalid --rotate argument. Must be positive integer" 1866 | Remove-Variable -name BkRotate -scope Script 1867 | } 1868 | Remove-Variable -name i -scope Local 1869 | } 1870 | 1871 | # -------------------------------------------------------------------------------------------------------------------------- 1872 | # Max Recursion Depth Policy - Checks 1873 | # -------------------------------------------------------------------------------------------------------------------------- 1874 | # Max depth to honor while scanning 1875 | If(Test-Variable "BkMaxDepth") { 1876 | Set-Variable -name i -value ([int]0) -scope Local 1877 | If(([system.int64]::tryparse($BkmaxDepth,[ref]$i))) { 1878 | Set-Variable -name BkMaxDepth -value $i -scope Script 1879 | If(($BkMaxDepth -lt 0)) { 1880 | Write-Output "Missing or invalid --maxdepth argument. Must be positive integer" 1881 | Remove-Variable -name BkMaxdepth -scope Script 1882 | } 1883 | } Else { 1884 | Write-Output "Missing or invalid --maxdepth argument. Must be positive integer" 1885 | Remove-Variable -name BkMaxDepth -scope Script 1886 | } 1887 | Remove-Variable -name i -scope Local 1888 | } 1889 | 1890 | # -------------------------------------------------------------------------------------------------------------------------- 1891 | # Email Notification - Checks 1892 | # -------------------------------------------------------------------------------------------------------------------------- 1893 | If(Test-Variable "BkNotifyLog") { 1894 | 1895 | # ---------------------------------------------------------------------------------------------------------------------- 1896 | # To Email Address(es) - Checks 1897 | # ---------------------------------------------------------------------------------------------------------------------- 1898 | If(!($BkNotifyLog -is [array])) { 1899 | Set-Variable -Name NotifyRecipients -value @($BkNotifyLog) -scope Script 1900 | $NotifyRecipients | Where-Object {!(IsValidEmailAddress $_)} | Write-Output ("Invalid --notify address {0}" -f $_) 1901 | $BkNotifyLog = @($NotifyRecipients | Where-Object {IsValidEmailAddress $_}) 1902 | Remove-Variable -Name NotifyRecipients -Scope Script 1903 | } Else { 1904 | $BkNotifyLog | Where-Object {!(IsValidEmailAddress $_)} | Write-Output ("Invalid --notify address {0}" -f $_) 1905 | $BkNotifyLog = @($BkNotifyLog | Where-Object {IsValidEmailAddress $_}) 1906 | } 1907 | If($BkNotifyLog.Count -lt 1) { 1908 | Remove-Variable -Name BkNotifyLog -Scope Script 1909 | } 1910 | 1911 | # ---------------------------------------------------------------------------------------------------------------------- 1912 | # To CC Email Address(es) - Checks 1913 | # ---------------------------------------------------------------------------------------------------------------------- 1914 | If(!($BkNotifyLogCc -is [array])) { 1915 | Set-Variable -Name NotifyRecipients -value @($BkNotifyLogCc) -scope Script 1916 | $NotifyRecipients | Where-Object {!(IsValidEmailAddress $_)} | Write-Output ("Invalid --notifyCc address {0}" -f $_) 1917 | $BkNotifyLogCc = @($NotifyRecipients | Where-Object {IsValidEmailAddress $_}) 1918 | Remove-Variable -Name NotifyRecipients -Scope Script 1919 | } Else { 1920 | $BkNotifyLogCc | Where-Object {!(IsValidEmailAddress $_)} | Write-Output ("Invalid --notifyCc address {0}" -f $_) 1921 | $BkNotifyLogCc = @($BkNotifyLogCc | Where-Object {IsValidEmailAddress $_}) 1922 | } 1923 | If($BkNotifyLogCc.Count -lt 1) { 1924 | Remove-Variable -Name BkNotifyLogCc -Scope Script 1925 | } 1926 | 1927 | # ---------------------------------------------------------------------------------------------------------------------- 1928 | # To BCC Email Address(es) - Checks 1929 | # ---------------------------------------------------------------------------------------------------------------------- 1930 | If(!($BkNotifyLogBcc -is [array])) { 1931 | Set-Variable -Name NotifyRecipients -value @($BkNotifyLogBcc) -scope Script 1932 | $NotifyRecipients | Where-Object {!(IsValidEmailAddress $_)} | Write-Output ("Invalid --notifyBcc address {0}" -f $_) 1933 | $BkNotifyLogBcc = @($NotifyRecipients | Where-Object {IsValidEmailAddress $_}) 1934 | Remove-Variable -Name NotifyRecipients -Scope Script 1935 | } Else { 1936 | $BkNotifyLogBcc | Where-Object {!(IsValidEmailAddress $_)} | Write-Output ("Invalid --notifyBcc address {0}" -f $_) 1937 | $BkNotifyLogBcc = @($BkNotifyLogBcc | Where-Object {IsValidEmailAddress $_}) 1938 | } 1939 | If($BkNotifyLogBcc.Count -lt 1) { 1940 | Remove-Variable -Name BkNotifyLogBcc -Scope Script 1941 | } 1942 | 1943 | # ---------------------------------------------------------------------------------------------------------------------- 1944 | # From Email Addresses - Checks 1945 | # ---------------------------------------------------------------------------------------------------------------------- 1946 | If(!(Test-Variable "BkSmtpFrom")) { 1947 | Write-Output "Missing or invalid --notifyfrom argument" 1948 | } Else { 1949 | If($BkSmtpFrom -is [array]) { $BkSmtpFrom = ($BkSmtpFrom -join "") } 1950 | If(!(IsValidEmailAddress $BkSmtpFrom)) { 1951 | Write-Output ("Missing or invalid --notifyfrom argument. {0} is not a valid email address" -f $BkSmtpFrom) 1952 | Remove-Variable -Name BkSmtpFrom -Scope Script 1953 | } 1954 | } 1955 | 1956 | # ---------------------------------------------------------------------------------------------------------------------- 1957 | # Email info - Checks 1958 | # ---------------------------------------------------------------------------------------------------------------------- 1959 | If(!(Test-Variable "BkNotifyExtra")) { Set-Variable -name BkNotifyExtra -value "none" -scope Script } 1960 | Switch ($BkNotifyExtra) { 1961 | "none" { Set-Variable -name BkNotifyExtra -value "none" -scope Script } 1962 | "inline" { Set-Variable -name BkNotifyExtra -value "inline" -scope Script } 1963 | "attach" { Set-Variable -name BkNotifyExtra -value "attach" -scope Script } 1964 | Default { Write-Output "Missing or invalid --notifyextra argument" ; Set-Variable -name BkNotifyExtra -value "none" -scope Script} 1965 | } 1966 | 1967 | # ---------------------------------------------------------------------------------------------------------------------- 1968 | # Relay server - Checks 1969 | # ---------------------------------------------------------------------------------------------------------------------- 1970 | If($BkSmtpRelay -is [array]) { $BkSmtpRelay = ($BkSmtpRelay -join "") } 1971 | If( 1972 | !(Test-Variable "BkSmtpRelay") -Or 1973 | (!(IsValidHostName $BkSmtpRelay) -And !(IsValidIPAddress $BkSmtpRelay)) 1974 | ) { 1975 | Write-Output "Missing or invalid --smtpserver argument" 1976 | Remove-Variable -Name BkSmtpRelay -Scope Script 1977 | } 1978 | 1979 | # ---------------------------------------------------------------------------------------------------------------------- 1980 | # Relay server authentication - Checks 1981 | # ---------------------------------------------------------------------------------------------------------------------- 1982 | If ( (Test-Variable "BkSmtpUser") -Or (Test-Variable "BkSmtpPass") ) { 1983 | If ( 1984 | !(Test-Variable "BkSmtpUser") -Or 1985 | !(Test-Variable "BkSmtpPass") -Or 1986 | ($BkSmtpUser -match "^\s*$") -Or 1987 | ($BkSmtpPass -match "^\s*$") 1988 | ) { 1989 | Write-Output "Missing or invalid --smtpuser or --smtppass argument" 1990 | Remove-Variable -Name BkSmtpUser 1991 | Remove-Variable -Name BkSmtpPass 1992 | } 1993 | } 1994 | 1995 | # ---------------------------------------------------------------------------------------------------------------------- 1996 | # Relay server port - Checks 1997 | # ---------------------------------------------------------------------------------------------------------------------- 1998 | If(!(Test-Variable "BkSmtpPort")) { Set-Variable -name BkSmtpPort -value ([int]25) -scope Script } Else { 1999 | Set-Variable -name i -value ([int]0) -scope Local 2000 | If(([system.int64]::tryparse($BkSmtpPort,[ref]$i))) { 2001 | Set-Variable -name BkSmtpPort -value $i -scope Script 2002 | If(($BkSmtpPort -le 0) -or ($BkSmtpPort -gt 65535)) { 2003 | Write-Output "Provided value for --smtpPort argument is not valid. Must be a number [1-65535]." 2004 | Remove-Variable -name BkSmtpPort -scope Script 2005 | } 2006 | } Else { 2007 | Write-Output "Provided value for --smtpPort argument is not valid. Must be a number [1-65535]." 2008 | Remove-Variable -name BkSmtpPort -scope Script 2009 | } 2010 | Remove-Variable -name i -scope Local 2011 | } 2012 | 2013 | } 2014 | 2015 | # -------------------------------------------------------------------------------------------------------------------------- 2016 | # 7z.exe binary - Checks 2017 | # -------------------------------------------------------------------------------------------------------------------------- 2018 | If(!(Test-Variable "Bk7ZipBin")) { 2019 | If(Test-Path -Path (Join-Path -Path ${Env:ProgramFiles} -ChildPath "\7-Zip\7z.exe") -PathType Leaf) { Set-Variable -Name Bk7ZipBin -value (Join-Path -Path ${Env:ProgramFiles} -ChildPath "\7-Zip\7z.exe") -scope Script} 2020 | If(Test-Path -Path (Join-Path -Path ${Env:ProgramFiles(x86)} -ChildPath "\7-Zip\7z.exe") -PathType Leaf) { Set-Variable -Name Bk7ZipBin -value (Join-Path -Path ${Env:ProgramFiles(x86)} -ChildPath "\7-Zip\7z.exe") -scope Script} 2021 | } 2022 | If( 2023 | !(Test-Variable "Bk7ZipBin") -Or 2024 | ($Bk7ZipBin -match "^\s*$") -Or 2025 | !(Test-Path -Path $Bk7ZipBin -pathType Leaf) 2026 | ) { Write-Output "Missing or invalid --7zipbin argument" } 2027 | Else 2028 | { 2029 | $MyContext.SevenZBinVersionInfo = @{} 2030 | Get-Item -Path $Bk7ZipBin | ForEach-Object { 2031 | $MyContext.SevenZBinVersionInfo.ProductVersion = $_.VersionInfo.ProductVersion.ToString() 2032 | $MyContext.SevenZBinVersionInfo.Major = $_.VersionInfo.ProductVersion.ToString().Split(".")[0] 2033 | $MyContext.SevenZBinVersionInfo.Minor = $_.VersionInfo.ProductVersion.ToString().Split(".")[1] 2034 | } 2035 | } 2036 | 2037 | # -------------------------------------------------------------------------------------------------------------------------- 2038 | # Junction.exe binary - Checks 2039 | # -------------------------------------------------------------------------------------------------------------------------- 2040 | # On Vista / 7 / 2008 native MKLINK is used instead 2041 | If([int]$MyContext.WinVer[0] -lt 6) { 2042 | 2043 | If(!(Test-Variable "BkJunctionBin")) { 2044 | ${Env:ProgramFiles}, ${Env:ProgramFiles(x86)} | ForEach-Object { 2045 | If(Test-Path -Path $_ -ChildPath "\SysInternalsSuite\junction.exe" -PathType Leaf) { 2046 | Set-Variable -Name BkJunctionBin -value (Join-Path -Path $_ -ChildPath "\SysInternalsSuite\junction.exe") -scope Script 2047 | } 2048 | } 2049 | } 2050 | 2051 | If( 2052 | !(Test-Variable "BkJunctionBin") -Or 2053 | ($BkJunctionBin -match "^\s*$") -Or 2054 | !(Test-Path -Path $BkJunctionBin -pathType Leaf) 2055 | ) 2056 | { Write-Output "Missing or invalid --jbin argument" } 2057 | } 2058 | 2059 | } 2060 | 2061 | # ==================================================================== 2062 | # End Functions Library 2063 | # ==================================================================== 2064 | # Start Script Flow Here 2065 | # ==================================================================== 2066 | 2067 | # This will prevent unhandled exit from the script 2068 | Try { 2069 | [console]::TreatControlCAsInput = $False 2070 | } Catch {} 2071 | 2072 | # Clean all script scoped variables beginning with "Bk" and "match" 2073 | Get-ChildItem variable:script:Bk* | Remove-Variable | Out-Null 2074 | Get-ChildItem variable:script:match* | Remove-Variable | Out-Null 2075 | 2076 | # -------------------------------------------------------------------- 2077 | # Initialize script scoped hashes 2078 | # -------------------------------------------------------------------- 2079 | Set-Variable -Name Counters -Value @{} -Scope Script 2080 | Set-Variable -Name SWriters -Value @{} -Scope Script 2081 | 2082 | $Counters.Exclusions = 0 2083 | $Counters.Warnings = 0 2084 | $Counters.Exceptions = 0 2085 | $Counters.Criticals = 0 2086 | $Counters.FoldersDone = 0 2087 | $Counters.FilesProcessed = 0 2088 | $Counters.FilesSelected = 0 2089 | $Counters.BytesSelected = [int64]0 2090 | $Counters.BytesAvailable = [int64]0 2091 | $Counters.PlaceHolders = @() 2092 | 2093 | # Output Header Text 2094 | Trace $headerText 2095 | 2096 | # Check For the presence of "--help" argument switch 2097 | If($args.length -ne 0) { 2098 | switch -wildcard ($args) { "*--help*" {Trace $helpText ; Try {[console]::TreatControlCAsInput = $False} Catch{} ; Return} } 2099 | } 2100 | 2101 | # Import hard coded variables if present -vars.ps1 script 2102 | Set-Variable -name BkVarsImportScript -value (Join-Path $MyContext.Directory $MyContext.Name.Replace(".ps1", "-vars.ps1")) -scope Script 2103 | If((Test-Path $BkVarsImportScript -pathType Leaf )) { 2104 | Try { & $BkVarsImportScript } 2105 | Catch { 2106 | Trace ("{0} reports an error thus has not been parsed" -f $BkVarsImportScript) 2107 | } 2108 | } 2109 | 2110 | Set-Variable -Name hasErrors -Value $False -Scope Script 2111 | Set-Variable -Name BkArguments -Value $args -Scope Script 2112 | 2113 | Validate-Arguments | ForEach-Object { $hasErrors = $True; Trace " Err : $_" } 2114 | Validate-Variables | ForEach-Object { $hasErrors = $True; Trace " Err : $_" } 2115 | If($hasErrors) { Trace ("`n Try .\{0} --help `n" -f $MyInvocation.MyCommand.Name); $Counters.Criticals = 1; Send-Notification; Return } 2116 | 2117 | 2118 | # -------------------------------------------------------------------- 2119 | # Do compose names 2120 | # -------------------------------------------------------------------- 2121 | Set-Variable -Name BkArchiveName -Value ($BkArchivePrefix + "-" + $BkType + "-" + (Get-Date -format "yyyyMMdd-HHmmss") + "." + $BkArchiveType) -Scope Script 2122 | Set-Variable -Name BkRootDir -Value ($BkWorkDrive + ":\~" + ([System.Guid]::NewGuid().ToString().Split("-")[1])) -Scope Script 2123 | Set-Variable -Name BkLockFile -Value (Join-Path $Env:Temp ($MyContext.Name.Substring(0, ($MyContext.Name.LastIndexOf("."))) + ".lock")) -scope Script 2124 | Set-Variable -Name BkSources -Value @{} -Scope Script 2125 | 2126 | Test-Lock | ForEach-Object { $hasErrors = $True; Trace " Err : $_" } 2127 | New-RootDir | ForEach-Object { $hasErrors = $True; Trace " Err : $_" } 2128 | Check-CTRLCRequest | Out-Null 2129 | 2130 | If($hasErrors) { 2131 | If(!($MyContext.Cancelling)) { 2132 | Do-PostAction 2133 | Send-Notification 2134 | } 2135 | Clear-Script 2136 | Return 2137 | } 2138 | 2139 | # -------------------------------------------------------------------------------- 2140 | # Execute pre Action if we have any (It may create directories we have to archive 2141 | # -------------------------------------------------------------------------------- 2142 | If(Test-Variable "BkPreAction") { 2143 | 2144 | Trace " Invoking Pre-Action (Output follows if any)" 2145 | Trace " ------------------------------------------------------------------------------" 2146 | Try { 2147 | & $BkPreAction 2>&1 | Set-Variable -Name preActionOutput -Scope Script 2148 | $preActionOutput | ForEach-Object { 2149 | Trace " $_" 2150 | } 2151 | } Catch { 2152 | Trace " $_.Exception.Message" 2153 | } 2154 | Trace " ------------------------------------------------------------------------------" 2155 | Trace " " 2156 | 2157 | } 2158 | 2159 | 2160 | # Initalize Operations 2161 | # Output all running context informations 2162 | Trace " Started on ........ : $((Get-Date -f "MMM dd, yyyy hh:mm:ss"))" 2163 | Trace " Backup Type ....... : $BkType" 2164 | If($BkClearBit -eq $True) { Trace " Files' Archive attr : Will be cleared" } Else { Trace " Files' Archive attr : Will stay unchanged" } 2165 | Trace " Selection File .... : $BkSelection" 2166 | If(Test-Variable "BkMaxDepth") { Trace " Recursion Depth ... : $BkMaxDepth" } 2167 | If($BkNoFollowJunctions) {Trace " Reparse points .... : Will NOT be followed" } 2168 | Trace " Destination ....... : $BkDestPath" 2169 | Trace " Archive Name ...... : $BkArchiveName" 2170 | Trace " Archive Type ...... : $BkArchiveType" 2171 | If((Test-Variable "BkRotate")) { Trace " Rotation policy ... : Keep last $BkRotate archive(s) " } Else { Trace " Rotation policy ... : Keep all archive(s) " } 2172 | Trace (" 7zip binary ....... : {0} (ver. {1}) " -f $Bk7zipBin,$MyContext.SevenZBinVersionInfo.ProductVersion) 2173 | Trace (" 7zip threading .... : {0} " -f ( & { If(Test-Variable "BkArchiveThreads") { Write-Output "$BkArchiveThreads threads" } Else { Write-Output "Auto"} })) 2174 | If(Test-Variable "BkArchiveCompression") { Trace " 7zip Compression .. : $BkArchiveCompression" } Else { Trace " 7zip Compression .. : Auto" } 2175 | Trace " " 2176 | Trace " ------------------------------------------------------------------------------" 2177 | 2178 | Trace " Backup From Sources " 2179 | Trace " ------------------------------------------------------------------------------" 2180 | # -------------------------------------------------------------------- 2181 | # Read the contents of selection file and create a junction for each one 2182 | # -------------------------------------------------------------------- 2183 | 2184 | $BkSelectionContents | Where-Object {$_ -imatch "^includesource=(.*)\|alias=(.*)"} | ForEach-Object { 2185 | 2186 | $directiveLine=[string]$_ 2187 | $directiveParts = $directiveLine.split("|", [System.StringSplitOptions]::RemoveEmptyEntries) 2188 | $target = $directiveParts[0].Split("=")[1] 2189 | $alias = $directiveParts[1].Split("=")[1] 2190 | 2191 | # Trace the selection 2192 | Trace " + $alias <== $Target" 2193 | 2194 | # Check target exist 2195 | If(!(Test-Path $target -pathType Container)) { 2196 | Trace " Selection directory $target does not exist. Skipping " 2197 | } Else { 2198 | 2199 | # Check alias is not already in use 2200 | If((Test-Path (Join-Path $BkRootDir $alias))) { 2201 | Trace " Alias $alias already in use. Skipping selection of $target" 2202 | } Else { 2203 | 2204 | If([int]$MyContext.WinVer[0] -lt 6 ) { 2205 | # Create the new junction for Windows previous to vista 2206 | If(!(Make-Junction (Join-Path -Path $BkRootDir -ChildPath $alias) $target)) { Trace " Failed to create Junction [$alias] to [$target]"} Else { $BkSources.Add($alias, $target) } 2207 | } Else { 2208 | # Create the new symbolic link for Windows Vista or newer 2209 | If(!(Make-SymLink (Join-Path -Path $BkRootDir -ChildPath $alias) $target)) { Trace " Failed to create Symbolic Link [$alias] to [$target]"} Else { $BkSources.Add($alias, $target) } 2210 | } 2211 | 2212 | } 2213 | 2214 | } 2215 | } 2216 | 2217 | # -------------------------------------------------------------------- 2218 | # Check we have at least one directory alias to backup 2219 | # -------------------------------------------------------------------- 2220 | If(( $BkSources.Count -eq 0 )) { 2221 | Trace " There are no selectable sources to backup. Quitting" 2222 | If(!($MyContext.Cancelling)) { 2223 | Do-PostAction 2224 | Send-Notification 2225 | } 2226 | Clear-Script 2227 | Return 2228 | } Else { 2229 | Trace " " 2230 | } 2231 | 2232 | # -------------------------------------------------------------------- 2233 | # Check we have an cleanup criteria on directories 2234 | # -------------------------------------------------------------------- 2235 | If($BkSelectionContents | Where-Object {$_ -match "^matchcleanupdirs="}) { 2236 | 2237 | Trace " Remove Directories Criteria" 2238 | Trace " ------------------------------------------------------------------------------" 2239 | $BkSelectionContents | Where-Object {$_ -match "^matchcleanupdirs="} | ForEach-Object { 2240 | $line = $_.Substring($_.IndexOf("=") + 1).Trim() 2241 | If(($line)) { 2242 | Trace " + Regex : $line" 2243 | If(!($matchcleanupdirs)) { $matchcleanupdirs = $line } Else { $matchcleanupdirs += ("|" + $line) } 2244 | } 2245 | } 2246 | Trace "`n All directories matching the above listed regular expressions will be deleted !!!`n" 2247 | } 2248 | 2249 | 2250 | # -------------------------------------------------------------------- 2251 | # Check we have an cleanup criteria on file names 2252 | # -------------------------------------------------------------------- 2253 | If($BkSelectionContents | Where-Object {$_ -match "^matchcleanupfiles="}) { 2254 | 2255 | Trace " Remove Files Criteria" 2256 | Trace " ------------------------------------------------------------------------------" 2257 | $BkSelectionContents | Where-Object {$_ -match "^matchcleanupfiles="} | ForEach-Object { 2258 | $line = $_.Substring($_.IndexOf("=") + 1).Trim() 2259 | If(($line)) { 2260 | Trace " + Regex : $line" 2261 | If(!($matchcleanupfiles)) { $matchcleanupfiles = $line } Else { $matchcleanupfiles += ("|" + $line) } 2262 | } 2263 | } 2264 | Trace "`n All files matching the above listed regular expressions will be deleted !!!" 2265 | } 2266 | 2267 | # -------------------------------------------------------------------- 2268 | # Check we have an exclude criteria on file names 2269 | # -------------------------------------------------------------------- 2270 | Trace "`n Files Inclusion Criteria " 2271 | Trace " ------------------------------------------------------------------------------" 2272 | $BkSelectionContents | Where-Object {$_ -match "^matchincludefiles="} | ForEach-Object { 2273 | $line = $_.Substring($_.IndexOf("=") + 1) 2274 | If(($line)) { 2275 | Trace " + Regex : $line" 2276 | If(!($matchincludefiles)) { $matchincludefiles = $line } Else { $matchincludefiles += ("|" + $line) } 2277 | } 2278 | } 2279 | If(!($matchincludefiles)) { Trace " + Any file name " } 2280 | 2281 | # -------------------------------------------------------------------- 2282 | # Check we have max/min fileage to honor 2283 | # -------------------------------------------------------------------- 2284 | If (Test-Variable "BkMaxFileAge") { Trace " + Max File Age : $BkMaxFileAge days" } 2285 | If (Test-Variable "BkMinFileAge") { Trace " + Min File Age : $BkMinFileAge days" } 2286 | 2287 | # -------------------------------------------------------------------- 2288 | # Check we have max/min filesize to honor 2289 | # -------------------------------------------------------------------- 2290 | If (Test-Variable "BkMaxFileSize") { Trace " + Max File Size : $BkMaxFileSize bytes" } 2291 | If (Test-Variable "BkMinFileSize") { Trace " + Min File Size : $BkMinFileSize bytes" } 2292 | 2293 | # -------------------------------------------------------------------- 2294 | # Check we have an exclude criteria on file names 2295 | # -------------------------------------------------------------------- 2296 | If($BkSelectionContents | Where-Object {$_ -match "^matchexcludefiles=*"}) { 2297 | Trace "`n Files Exclusion Criteria " 2298 | Trace " ------------------------------------------------------------------------------" 2299 | $BkSelectionContents | Where-Object {$_ -match "^matchexcludefiles=*"} | ForEach-Object { 2300 | $line = $_.Substring($_.IndexOf("=") + 1).Trim() 2301 | If(($line)) { 2302 | Trace " - Regex : $line" 2303 | If(!($matchexcludefiles)) { $matchexcludefiles = $line } Else { $matchexcludefiles += ("|" + $line) } 2304 | } 2305 | } 2306 | If(!($matchexcludefiles)) { Trace " None " } 2307 | Trace "`n All files matching the above listed regular expressions `n WILL NOT BE INCLUDED IN BACKUP !!!" 2308 | } 2309 | 2310 | # -------------------------------------------------------------------- 2311 | # Check we have an exclude criteria on paths 2312 | # -------------------------------------------------------------------- 2313 | If($BkSelectionContents | Where-Object {$_ -match "^matchexcludepath=*"}) { 2314 | Trace "`n Exclude Paths Criteria " 2315 | Trace " ------------------------------------------------------------------------------" 2316 | $BkSelectionContents | Where-Object {$_ -match "^matchexcludepath=*"} | ForEach-Object { 2317 | $line = $_.Substring($_.IndexOf("=") + 1).Trim() 2318 | If(($line)) { 2319 | Trace " -match $line" 2320 | If(!($matchexcludepath)) { $matchexcludepath = $line } Else { $matchexcludepath += ("|" + $line) } 2321 | } 2322 | } 2323 | If(!($matchexcludepath)) { Trace " None "} 2324 | Trace "`n All directories matching the above listed regular expressions `n WILL NOT BE INCLUDED IN BACKUP !!!" 2325 | } 2326 | # -------------------------------------------------------------------- 2327 | # Check we have any rule to stop digging into directories 2328 | # -------------------------------------------------------------------- 2329 | If($BkSelectionContents | Where-Object {$_ -match "^matchstoprecurse=*"}) { 2330 | Trace "`n Stop Recursion Criteria " 2331 | Trace " ------------------------------------------------------------------------------" 2332 | $BkSelectionContents | Where-Object {$_ -match "^matchstoprecurse=*"} | ForEach-Object { 2333 | $line = $_.Substring($_.IndexOf("=") + 1).Trim() 2334 | If(($line)) { 2335 | Trace " -match $line" 2336 | If(!($matchstoprecurse)) { $matchstoprecurse = $line } Else { $matchstoprecurse += ("|" + $line) } 2337 | } 2338 | } 2339 | If(!($matchstoprecurse)) { Trace " None " } 2340 | Trace "`n All directories matching the above listed regular expressions `n WILL NOT BE RECURSED !!!" 2341 | } 2342 | 2343 | # -------------------------------------------------------------------- 2344 | # Move to the $BkRootDir and make it current 2345 | # -------------------------------------------------------------------- 2346 | Set-Location -path $BkRootDir 2347 | 2348 | # -------------------------------------------------------------------- 2349 | # Let's drop into $BkRootDir a few files which will contain useful 2350 | # information in case you want to examine the contents of an archive 2351 | # and how it's been generated. 2352 | # -------------------------------------------------------------------- 2353 | $BkSelectionInfo = Join-Path $BkRootDir "Selection-Info.txt" ; New-Item $BkSelectionInfo -type File -Force -value ([string]::join([environment]::newline, (Get-Content -path $BkSelection -encoding ASCII))) | Out-Null 2354 | $BkSelectionExcpt = Join-Path $BkRootDir "Selection-Excpt.csv"; New-Item $BkSelectionExcpt -type File -Force | Out-Null; "Id`tException`tTarget" | Out-File $BkCatalogExclude -encoding ASCII -append 2355 | $BkCatalogInclude = Join-Path $BkRootDir "Catalog-Include.txt"; New-Item $BkCatalogInclude -type File -Force | Out-Null 2356 | $BkCatalogExclude = Join-Path $BkRootDir "Catalog-Exclude.csv"; New-Item $BkCatalogExclude -type File -Force | Out-Null; "Id`tDirective`tType`tTarget" | Out-File $BkCatalogExclude -encoding ASCII -append 2357 | $BkCatalogStats = Join-Path $BkRootDir "Catalog-Stats.csv" ; New-Item $BkCatalogStats -type File -Force | Out-Null; "Id`tExtension`tSize" | Out-File $BkCatalogStats -encoding ASCII -append 2358 | $BkCompressDetail = Join-Path $BkRootDir "Compress-Detail.txt"; New-Item $BkCompressDetail -type File -Force | Out-Null 2359 | 2360 | # -------------------------------------------------------------------- 2361 | # Open StreamWriters for optimize performance. 2362 | # Out-File and Add-Content are rubbish and cause the selection to be 2363 | # up to 20x slower 2364 | # -------------------------------------------------------------------- 2365 | $SWriters.Inclusions = New-Object -TypeName System.IO.StreamWriter($BkCatalogInclude, [String]$True, [System.Text.Encoding]::UTF8) 2366 | $SWriters.Exclusions = New-Object -TypeName System.IO.StreamWriter($BkCatalogExclude, [String]$True, [System.Text.Encoding]::ASCII) 2367 | $SWriters.Exceptions = New-Object -TypeName System.IO.StreamWriter($BkCatalogExceptions, [String]$True, [System.Text.Encoding]::ASCII) 2368 | $SWriters.Stats = New-Object -TypeName System.IO.StreamWriter($BkCatalogStats, [String]$True, [System.Text.Encoding]::ASCII) 2369 | $SWriters.GetEnumerator() | ForEach-Object { $_.Value.AutoFlush = $True } 2370 | 2371 | Trace " " 2372 | Trace " Scanning Directories and Files ..." 2373 | Trace " ------------------------------------------------------------------------------" 2374 | 2375 | # Begin the processing of the root folder to build up the catalogs and start counting elapsed time 2376 | $MyContext.SelectionStart = Get-Date 2377 | 2378 | # Look-up for the folders (which are junctions) in the Root Folder 2379 | Set-Variable -Name catalogFolders -value (New-Object System.Collections.ArrayList) -scope Script 2380 | Set-Variable -Name catalogFoldersIndex -value ([int]0) -scope Script 2381 | $BkSources.GetEnumerator() | ForEach-Object { 2382 | 2383 | $itemFolder = @{} 2384 | $itemFolder.Name = $_.Name 2385 | $itemFolder.FullName = Join-Path -Path $BkRootDir -ChildPath $_.Value 2386 | $itemFolder.RelativeName = $_.Name 2387 | $itemFolder.ContainerAlias = $_.Name 2388 | $itemFolder.RealName = Join-Path -Path $BkSources[$itemFolder.ContainerAlias] -ChildPath ($itemFolder.RelativeName.Replace($itemFolder.ContainerAlias, "")) 2389 | $itemFolder.Depth = 0; 2390 | [void] $catalogFolders.Add($itemFolder) 2391 | 2392 | } 2393 | 2394 | # Walk through catalogFolders to process each one 2395 | While ($True) { 2396 | If(Check-CTRLCRequest) {break} 2397 | ProcessFolder $catalogFolders[$catalogFoldersIndex] | Out-Null 2398 | If (!(++$catalogFoldersIndex -le $catalogFolders.Count)) {Write-Progress -Activity "." -Status "." -Completed; break} 2399 | } 2400 | If($MyContext.Cancelling) { 2401 | If(!($MyContext.Cancelling)) { Do-PostAction; Send-Notification } 2402 | Clear-Script 2403 | Return 2404 | } 2405 | 2406 | # Add Support Files to archive selection 2407 | If($Counters.FilesSelected -gt 0) { 2408 | Get-ChildItem -Path $BkRootDir -Force | ? {!$_.PSIsContainer} | ForEach-Object { 2409 | if( 2410 | ($_.Name -notmatch "stats") -And 2411 | ($_.Name -notmatch "README") -And 2412 | ($_.Name -notmatch "^Compress-Details.txt") 2413 | ) { 2414 | $Counters.FilesSelected++ ; 2415 | $Counters.BytesSelected += $_.Length ; 2416 | $SWriters.Inclusions.WriteLine($_.Name) 2417 | $SWriters.Stats.WriteLine([string]("{0}`t{1}`t{2}" -f $Counters.FilesSelected,$_.Extension,[string]$_.Length )) 2418 | } 2419 | } 2420 | } 2421 | 2422 | # Include non existent file 2423 | # $SWriters.Inclusions.WriteLine("qwerty.txt") 2424 | 2425 | # -------------------------------------------------------------------- 2426 | # Close StreamWriters letting enough time to flush buffers 2427 | # -------------------------------------------------------------------- 2428 | $SWriters.GetEnumerator() | ForEach-Object { 2429 | $_.Value.Flush() 2430 | If($_.Name -notmatch "^Log$") {$_.Value.Close()} 2431 | } -End { Start-Sleep -Milliseconds 500 } 2432 | 2433 | 2434 | # Calc of elapsed time for selection process 2435 | $MyContext.SelectionEnd = Get-Date 2436 | $MyContext.SelectionElapsed = New-TimeSpan $MyContext.SelectionStart $MyContext.SelectionEnd 2437 | 2438 | # Trace informations about what is selected 2439 | Trace (" Phase time : {0,0:n0} d : {1,0:n0} h : {2,0:n0} m : {3,0:n3} s" -f $MyContext.SelectionElapsed.Days, $MyContext.SelectionElapsed.Hours, $MyContext.SelectionElapsed.Minutes, ($MyContext.SelectionElapsed.Seconds + ($MyContext.SelectionElapsed.MilliSeconds/1000)) ) 2440 | Trace (" Selected : {0,0:n0} out of {1,0:n0} files in {2,0:n0} folders. {3,0:n2} MBytes to backup" -f $Counters.FilesSelected, $Counters.FilesProcessed, $Counters.FoldersDone, ($Counters.BytesSelected/1mb)) 2441 | Trace (" Performance : {0,0:n2} files/sec " -f ( $Counters.FilesProcessed / $MyContext.SelectionElapsed.TotalSeconds ) ) 2442 | 2443 | 2444 | # Early exit from the process if user cancel or there is nothingto backup 2445 | If(($Counters.FilesSelected -lt 1) -or (Check-CTRLCRequest)) { 2446 | 2447 | # Trace we have not selected anything to backup 2448 | Trace " " 2449 | Trace " There are no files matching the selection criteria. Possible reasons: " 2450 | Trace " - All source directories are empty and choose not to keep them" 2451 | Trace " - No file match selection criteria" 2452 | Trace " - User Cancel Request (CTRL+C)" 2453 | Trace " " 2454 | 2455 | If(!($MyContext.Cancelling)) { 2456 | Do-PostAction 2457 | Send-Notification 2458 | } 2459 | Clear-Script 2460 | Return 2461 | 2462 | } 2463 | 2464 | # Adjust at least 1byte selected (in case all files are zero length) 2465 | # This will prevent division by zero errors 2466 | If(($Counters.BytesSelected -lt 1)) { $Counters.BytesSelected = 1 } 2467 | 2468 | 2469 | # Maybe there has been some exceptions during the selection progress. 2470 | # If this is the case output them here. 2471 | If((Get-Item $BkSelectionExcpt).Length -gt 0) { 2472 | Trace "`n Exceptions during selection process" 2473 | Trace " ------------------------------------------------------------------------------" 2474 | Get-Content $BkSelectionExcpt | ForEach-Object { 2475 | Trace (" {0} " -f $_); $Counters.Warnings++ 2476 | } 2477 | } 2478 | 2479 | If(!(Check-CTRLCRequest -eq $True)) { 2480 | # Do some stats (many thanks to http://www.hanselman.com/blog/ParsingCSVsAndPoorMansWebLogAnalysisWithPowerShell.aspx) 2481 | Write-Progress -Activity "Calculating Stats on Selection" -Status "Running ..." -CurrentOperation "Please Wait ..." 2482 | $statsByExtension = Import-Csv $BkCatalogStats -Delimiter "`t" | Select-Object Extension, Size | group Extension | select Name, @{Name="Count";Expression={($_.Count)}}, @{Name="Size";Expression={($_.Group | Measure-Object -Sum Size).Sum }} | Sort Size -desc 2483 | Write-Progress -Activity "." -Status "." -Completed 2484 | 2485 | # Output summarized data 2486 | Trace " " 2487 | Trace " Selection Details" $BkCatalogStats 2488 | Trace " ------------------------------------------------------------------------------" 2489 | Trace " Extension Count Total MB Abs % Inc % " 2490 | Trace " ------------------------------- ----------- ----------------- ------- -------" 2491 | $totalCount = 0; [int64]$totalBytes = 0 2492 | $statsByExtension | ForEach-Object { 2493 | $totalCount += $_.Count ; $totalBytes += $_.Size 2494 | Trace (" {0,-31} {1,11:n0} {2,17:n2} {3,6:n2} {4,6:n2}" -f $_.Name, $_.Count, ($_.Size/1MB), ($_.Size/ $Counters.BytesSelected * 100), ($totalBytes / $Counters.BytesSelected * 100)) 2495 | } 2496 | Trace " ----------- ----------------- " 2497 | Trace (" {0,-31} {1,11:n0} {2,17:n2}" -f "Total", $totalCount, ($totalBytes/1MB)) 2498 | Trace " =========== ================= `n" 2499 | 2500 | 2501 | } 2502 | 2503 | 2504 | If($BkDryRun -ne $True) { 2505 | 2506 | # Check we have enough disk space available on target path 2507 | $Counters.BytesAvailable = ([int64](GetDestPathFreeSpace -target $BkDestPath)) 2508 | If($Counters.BytesAvailable -lt ($totalBytes * 1)) { 2509 | Trace (" Warning !! ... you're low on space on target ") 2510 | Trace (" {0,-31} {1,17:n2}" -f " Required Max..............", ($totalBytes/1MB)) 2511 | Trace (" {0,-31} {1,17:n2}" -f " Available ...............", ($Counters.BytesAvailable/1MB)) 2512 | Trace (" If 7zip cannot compress enough it will fail `n") 2513 | } 2514 | 2515 | 2516 | $BkDestFile = (Join-Path -Path $BkDestPath -ChildPath $BkArchiveName) 2517 | Write-Progress -Activity "Archiving into $BkDestFile" -Status "Please wait ..." -CurrentOperation "Initializing ..." 2518 | 2519 | # Compose arguments which will be passed to command line 2520 | $Bk7ZipArgs = @() 2521 | $Bk7ZipArgs += "a" # This is the "add" switch (means add and update) 2522 | $Bk7ZipArgs += "-ssw" # Archive files open for writing 2523 | $Bk7ZipArgs += "-slp" # Use large memory pages 2524 | 2525 | If((Test-Variable "BkArchiveCompression") -And ($BkArchiveType -ne "tar")) { # Set compression level 2526 | $Bk7ZipArgs += ("-mx{0}" -f $BkArchiveCompression) 2527 | } 2528 | # Important !!! 2529 | $Bk7ZipArgs += "-scsUTF-8" # Set charset for list files to UTF8 2530 | $Bk7ZipArgs += "-sccDOS" # Set charset for console input/output to DOS (OEM) Windows 2531 | 2532 | # If 7zip is beyond version 9.2 then add some more switches 2533 | If ([int]$MyContext.SevenZBinVersionInfo.Major -ge 15) { 2534 | $Bk7ZipArgs += "-bd" # Disable Progress indicator 2535 | $Bk7ZipArgs += "-bb1" 2536 | $Bk7ZipArgs += "-bsp0" 2537 | $Bk7ZipArgs += "-bso1" 2538 | $Bk7ZipArgs += "-bse2" 2539 | If($BkArchiveType -eq "7z") { 2540 | $Bk7ZipArgs += "-mtm=on" # Stores last Modified timestamps for files. 2541 | $Bk7ZipArgs += "-mtc=on" # Stores Creation timestamps for files. 2542 | $Bk7ZipArgs += "-mta=on" # Stores last Access timestamps for files. 2543 | } 2544 | } Else { 2545 | $Bk7ZipArgs += "-bd" # Disable Progress indicator 2546 | } 2547 | 2548 | # Control Threading 2549 | If(Test-Variable "BkArchiveThreads") { 2550 | If($BkArchiveThreads -lt 1) { 2551 | $Bk7ZipArgs += "-mmt=off" # Disable multi threading 2552 | } Else { 2553 | $Bk7ZipArgs += ("-mmt={0}" -f $BkArchiveThreads) # Use exact number of threads 2554 | } 2555 | } 2556 | 2557 | # Control solid archives 2558 | If(($BkArchiveType -eq "7z") -And !($BkArchiveSolid)) { 2559 | $Bk7ZipArgs += "-ms=off" # Disable solid archive 2560 | } 2561 | 2562 | # Control volumes # Apply Volumes Policies 2563 | If((Test-Variable "BkArchiveVolumes") -eq $True) { 2564 | $BkArchiveVolumes | ForEach-Object { 2565 | $Bk7ZipArgs += ("-v{0}" -f $_) 2566 | } 2567 | } 2568 | 2569 | $Bk7ZipArgs += "-t" + $BkArchiveType # This is the type of the archive 2570 | If(Test-Variable "BkArchivePassword") { 2571 | $Bk7ZipArgs += "-p$BkArchivePassword" # This is the password (if any) 2572 | If($BkEncryptHeaders) { $Bk7ZipArgs += "-mhe" } 2573 | } 2574 | 2575 | 2576 | $Bk7ZipArgs += "`"$BkDestFile`"" # This is the destination file 2577 | $Bk7ZipArgs += "`@`"$BkCatalogInclude`"" # This is the catalog input file 2578 | 2579 | # Create Process 2580 | If(Test-Variable "Bk7ZipRetc") { Remove-Variable -Name Bk7ZipRetc } 2581 | $oProcessStartInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo 2582 | $oProcessStartInfo.FileName = $Bk7ZipBin 2583 | $oProcessStartInfo.WorkingDirectory = $BkRootDir 2584 | $oProcessStartInfo.RedirectStandardError = $true 2585 | $oProcessStartInfo.RedirectStandardOutput = $true 2586 | $oProcessStartInfo.UseShellExecute = $false 2587 | $oProcessStartInfo.CreateNoWindow = $true 2588 | $oProcessStartInfo.Arguments = ($Bk7ZipArgs -join " ") 2589 | Write-Verbose "7z arguments: $($Bk7ZipArgs -join ' ')" 2590 | $oProcess = New-Object -Typename System.Diagnostics.Process 2591 | $oProcess.StartInfo = $oProcessStartInfo 2592 | 2593 | # Initialize StreamWriter for Compress Details 2594 | $SWriters.CompressDetail = New-Object -TypeName System.IO.StreamWriter($BkCompressDetail, [String]$True, [System.Text.Encoding]::UTF8) 2595 | $SWriters.CompressDetail.AutoFlush = $True 2596 | 2597 | # Initialize StringBuilder for StdErr 2598 | $oStdErrBuilder = New-Object -TypeName System.Text.StringBuilder 2599 | 2600 | # Adding event handers for stdout and stderr. 2601 | $stdOutScripBlock = { if (! [String]::IsNullOrEmpty($EventArgs.Data)) { $Event.MessageData.WriteLine($EventArgs.Data) } } 2602 | $stdErrScripBlock = { if (! [String]::IsNullOrEmpty($EventArgs.Data)) { $Event.MessageData.Append(" " + $EventArgs.Data) | Out-Null } } 2603 | 2604 | # Register Event Handlers 2605 | $oStdOutEvent = Register-ObjectEvent -InputObject $oProcess -Action $stdOutScripBlock -EventName 'OutputDataReceived' -MessageData $SWriters.CompressDetail 2606 | $oStdErrEvent = Register-ObjectEvent -InputObject $oProcess -Action $stdErrScripBlock -EventName 'ErrorDataReceived' -MessageData $oStdErrBuilder 2607 | 2608 | # Start the clocks 2609 | $MyContext.CompressionStart = Get-Date 2610 | 2611 | # Start Process 2612 | [void]$oProcess.Start() 2613 | [void]$oProcess.BeginOutputReadLine() 2614 | [void]$oProcess.BeginErrorReadLine() 2615 | $lastStdErrLine = 0 2616 | 2617 | # Begin polling Process 2618 | While (!($oProcess.HasExited)) { 2619 | Start-Sleep -Milliseconds 2500 2620 | $Status = "Waiting for archive ..." 2621 | $ArchiveSize = 0 2622 | Get-ChildItem -Path $BkDestPath -Filter ("{0}*" -f $BkArchiveName) | ?{ !$_.PSIscontainer } | ForEach-Object { $ArchiveSize += $_.Length } 2623 | If ( $ArchiveSize -gt 0 ) { $Status = "Archive Size {0,0:n2} MByte. so far ..." -f ($ArchiveSize / 1Mb) } 2624 | 2625 | # Look for any message from 7z in stdErr queue 2626 | $oStdErrBuilderLines = @($oStdErrBuilder.ToString().Split([System.Environment]::NewLine)) 2627 | if($oStdErrBuilderLines.Count -gt 0) { 2628 | $i = 0 2629 | $oStdErrBuilderLines | ForEach-Object { 2630 | $i++ 2631 | If($i -gt $lastStdErrLine) { 2632 | If($_.ToString().Length -gt 0) {Trace (" !{0}" -f $_.ToString()); $lastStdErrLine = $i} 2633 | } 2634 | } 2635 | } 2636 | 2637 | 2638 | Write-Progress -Activity "Archiving into $BkDestFile" -Status $Status -CurrentOperation "Please wait ..." 2639 | If(Check-CTRLCRequest -eq $True) { 2640 | [void]$oProcess.Kill() 2641 | While (!($oProcess.HasExited)) { Start-Sleep -Milliseconds 100 } 2642 | Set-Variable -Name Bk7ZipRetc -value ([int]255) -scope Script # Force return code to 255 2643 | Start-Sleep -Milliseconds 500 2644 | # Delete the destination file 2645 | If(Test-Path -Path $BkDestFile -PathType Leaf) { Remove-Item -LiteralPath $BkDestFile -Force | Out-Null } 2646 | break 2647 | } 2648 | } 2649 | 2650 | # Retrieve ExitCode if not already defined 2651 | If(!(Test-Variable "Bk7ZipRetc")) { Set-Variable -Name "Bk7ZipRetc" -value $oProcess.ExitCode -scope Script } 2652 | 2653 | # Stop the clock 2654 | $MyContext.CompressionEnd = Get-Date 2655 | $MyContext.CompressionElapsed = New-TimeSpan $MyContext.CompressionStart $MyContext.CompressionEnd 2656 | 2657 | # Remove event handlers 2658 | Unregister-Event -SourceIdentifier $oStdOutEvent.Name 2659 | Unregister-Event -SourceIdentifier $oStdErrEvent.Name 2660 | 2661 | # Close StreamWriter for Compress Details 2662 | $SWriters.CompressDetail.Flush() 2663 | $SWriters.CompressDetail.Close() 2664 | $SWriters.CompressDetail.Dispose() 2665 | 2666 | # Version 9.x and 15.x of 7zip have different outputs 2667 | # Look inside $BkCompressDetail in search of any file which may have been skipped 2668 | # e.g. 7-Zip could not find one or more selected files 2669 | If ([int]$MyContext.SevenZBinVersionInfo.Major -le 9) { 2670 | $relevantMessages = Get-Content $BkCompressDetail -encoding UTF8 | Where-Object {$_ -match "\ WARNING:\ |\ :\ "} 2671 | } else { 2672 | $relevantMessages = Get-Content $BkCompressDetail -encoding UTF8 | Where-Object {$_ -match "[A-Z]{1}\:\\.* \:\ .{1,}$"} 2673 | } 2674 | 2675 | #If any relevant message then output 2676 | If(!($Bk7ZipRetc -eq 255) -and $relevantMessages) { 2677 | Trace " 7-Zip completed with warnings " 2678 | Trace " ------------------------------------------------------------------------------" 2679 | $relevantMessages | ForEach-Object { 2680 | Trace " $_"; $Counters.Warnings++ 2681 | } 2682 | Trace " " 2683 | } 2684 | 2685 | # Check overall size of archive (including volumes if present) 2686 | $ArchiveSize = 0 2687 | Get-ChildItem -Path $BkDestPath -Filter ("{0}*" -f $BkArchiveName) | ?{ !$_.PSIscontainer } | ForEach-Object { $ArchiveSize += $_.Length } 2688 | 2689 | # Check exit code by 7zip - If ErrorLevel is <2 then we assume backup 2690 | # process completed successfully 2691 | If(($Bk7ZipRetc -lt 2) -and ($ArchiveSize -gt 0) -and !(Check-CTRLCRequest)) { 2692 | 2693 | # Output informations in log file 2694 | Trace (" Created : {1} in {0} " -f $BkDestPath, $BkArchiveName) 2695 | Trace (" Archive Size : {0,0:n2} MB = {1,2:n2}% of original size" -f ($ArchiveSize / 1Mb), ((($ArchiveSize / $Counters.BytesSelected)) * 100)) 2696 | Trace (" 7zip time : {0,0:n0} d : {1,0:n0} h : {2,0:n0} m : {3,0:n3} s" -f $MyContext.CompressionElapsed.Days, $MyContext.CompressionElapsed.Hours, $MyContext.CompressionElapsed.Minutes, ($MyContext.CompressionElapsed.Seconds + $MyContext.CompressionElapsed.Milliseconds / 1000) ) 2697 | Trace (" Performance : {0,0:n2} files/sec" -f ($Counters.FilesSelected / $MyContext.CompressionElapsed.TotalSeconds) ) 2698 | Trace (" IO Avg Speed : Read {0,0:n2} MB/Sec / Write {1,0:n2} MB/Sec" -f (($Counters.BytesSelected / $MyContext.CompressionElapsed.TotalSeconds) / 1MB), (($ArchiveSize / $MyContext.CompressionElapsed.TotalSeconds) / 1MB) ) 2699 | Trace " " 2700 | 2701 | 2702 | # Do Post Archiving 2703 | If(!(Check-CTRLCRequest)) { PostArchiving ; } 2704 | 2705 | # Do rotation over backup files 2706 | # We have to list all files in the destination directory matching the same prefix and the same type 2707 | # list all items descending (by their creation date) and then delete the oldest out of 2708 | # the rotation range. If no rotation is defined then assume rotation period is 999 so we 2709 | # can easily have an output of archives on target media. 2710 | If(!(Check-CTRLCRequest)) { 2711 | If(!(Test-Variable "BkRotate")) { Set-Variable -name "BkRotate" -value ([int]9999) -scope Script } 2712 | If(($BkRotate -ge 1)) { 2713 | $totalArchiveBytes = [int64]0 2714 | $fileNameRgx = ("$([Regex]::Escape($BkArchivePrefix))-$BkType-[0-9]{8}-[0-9]{4,6}\.(7z|zip|tar)(\.\d{3})?") 2715 | Trace " Archives in $BkDestPath" 2716 | Trace " ------------------------------------------------------------------------------" 2717 | Get-ChildItem $BkDestPath | ?{ $_.Name -match $fileNameRgx -and !$_.PSIscontainer } | sort @{expression={$_.Name};Descending=$true} | foreach-object { 2718 | If(!($BkRotate -le 0)) { 2719 | If ($_.Name -match ([Regex]::Escape($BkArchiveName))) { 2720 | Trace (" New : {0,-48} {1,15:n2} MB " -f $_.Name, $($_.Length / 1MB) ); $totalArchiveBytes += [int64]$_.Length 2721 | } Else { 2722 | Trace (" Kept : {0,-48} {1,15:n2} MB " -f $_.Name, $($_.Length / 1MB) ); $totalArchiveBytes += [int64]$_.Length 2723 | } 2724 | 2725 | # Check is volumized archive 2726 | If ( (($_.Name -match "(.*)(7z|zip|tar)\.\d{3}$") -and ($_.Name.EndsWith("001"))) -or ($_.Name -match "(.*)(7z|zip|tar)$") ) { 2727 | $BkRotate += -1 2728 | } 2729 | 2730 | } Else { 2731 | Remove-Item -LiteralPath (Join-Path $BkDestPath $_.Name) -ErrorAction "SilentlyContinue" | Out-Null 2732 | if ($?) { Trace (" Removed : {0,-48} {1,15:n2} MB " -f $_.Name, $($_.Length / 1MB) ) } Else { Trace " WARNING Failed to remove $_.Name"} 2733 | } 2734 | } 2735 | Trace " ------------------------------------------------------------------------------" 2736 | Trace (" {0,-59} {1,15:n2} MB" -f "Used space by listed archives (New and Kept)", $($totalArchiveBytes / 1MB) ) 2737 | Trace (" {0,-59} {1,15:n2} MB" -f "Remaining Free space on target", $((([int64](GetDestPathFreeSpace -target $BkDestPath))) / 1MB) ) 2738 | Trace " ------------------------------------------------------------------------------`n" 2739 | 2740 | } 2741 | } 2742 | 2743 | If(($Counters.Warnings -gt 0)) { 2744 | Trace (" Task status : Done with : " + $Counters.Warnings + " warnings. Check logs!") 2745 | } Else { 2746 | Trace " Task status : All Done !! Yuppieee" 2747 | } 2748 | $MyContext.TotalElapsed = New-TimeSpan $MyContext.SelectionStart $(Get-Date) 2749 | Trace (" Task time : {0,0:n0} d : {1,0:n0} h : {2,0:n0} m : {3,0:n0} s" -f $MyContext.TotalElapsed.Days, $MyContext.TotalElapsed.Hours, $MyContext.TotalElapsed.Minutes, $MyContext.TotalElapsed.Seconds ) 2750 | Trace (" Task end : {0}`n" -f (Get-Date -f "MMM dd, yyyy hh:mm:ss") ) 2751 | 2752 | } Else { 2753 | 2754 | # Uncomment this line if you want to read the details of 7-Zip log of operations 2755 | #[string]::join([environment]::newline, (Get-Content -path $BkCompressDetail -encoding ASCII)) 2756 | 2757 | # If we fall down here the 7z.exe has exited with a high error level 2758 | # According to 7-Zip manual the possibilities are: 2759 | # 0 - No error 2760 | # 1 - Warning (Non fatal error(s)). For example, one or more files were locked by some other application, so they were not compressed 2761 | # 2 - Fatal error 2762 | # 7 - Command line error 2763 | # 8 - Not Enough memory to complete operation 2764 | # 255 - User stopped the process 2765 | If (($Bk7ZipRetc -eq 255)) { 2766 | $Counters.Criticals += 1 2767 | Trace " " 2768 | Trace " Cancelled ! User has stopped 7-Zip archiving process" 2769 | Trace " NO ARCHIVE HAS BEEN CREATED" 2770 | If(Test-Path -Path $BkDestFile -PathType Leaf) { Remove-Item -LiteralPath $BkDestFile -Force | Out-Null } 2771 | } ElseIf (($Bk7ZipRetc -eq 2)) { 2772 | $Counters.Criticals += 1 2773 | Trace " " 2774 | Trace " Cancelled ! 7-Zip reported a fatal error." 2775 | Trace " NO VALID ARCHIVE HAS BEEN CREATED" 2776 | If(Test-Path -Path $BkDestFile -PathType Leaf) { Remove-Item -LiteralPath $BkDestFile -Force | Out-Null } 2777 | } ElseIf (($Bk7ZipRetc -eq 7)) { 2778 | $Counters.Criticals += 1 2779 | Trace " " 2780 | Trace " Cancelled ! 7-Zip has been invoked with a wrong command line." 2781 | Trace " $cmdLine" 2782 | Trace " NO VALID ARCHIVE HAS BEEN CREATED" 2783 | If(Test-Path -Path $BkDestFile -PathType Leaf) { Remove-Item -LiteralPath $BkDestFile -Force | Out-Null } 2784 | } ElseIf (($Bk7ZipRetc -eq 8)) { 2785 | $Counters.Criticals += 1 2786 | Trace " " 2787 | Trace " Cancelled ! 7-Zip reports not enough memory." 2788 | Trace " NO VALID ARCHIVE HAS BEEN CREATED" 2789 | If(Test-Path -Path $BkDestFile -PathType Leaf) { Remove-Item -LiteralPath $BkDestFile -Force | Out-Null } 2790 | } ElseIf (!(Test-Path -Path "$BkDestPath\$BkArchiveName" -PathType Leaf)) { 2791 | $Counters.Criticals += 1 2792 | Trace " " 2793 | Trace " Error !" 2794 | Trace " NO ARCHIVE HAS BEEN CREATED" 2795 | } 2796 | 2797 | 2798 | } 2799 | } 2800 | Else { 2801 | Trace " Dry Run Selected ! No Archive creation." 2802 | } 2803 | 2804 | # If is set a list of notification addresses then proceed with email here 2805 | if (!(Check-CTRLCRequest)) { 2806 | Do-PostAction 2807 | Send-Notification 2808 | } 2809 | 2810 | # Clean Up 2811 | Clear-Script 2812 | -------------------------------------------------------------------------------- /7zBackup.selection.sample.txt: -------------------------------------------------------------------------------- 1 | # ******************************************************************** 2 | # This is the 7zBackup Selection And Job Specification File 3 | # ******************************************************************** 4 | # TAG: prefix 5 | # 6 | # The prefix to use to generate the archive name. 7 | # If not defined then the archive name is generated using the 8 | # rules held in the vars file. If yet missing is automatically 9 | # generated using the computername. 10 | # 11 | # Example 12 | # prefix=MYArchiveName 13 | # 14 | # Default 15 | # prefix= 16 | 17 | # ******************************************************************** 18 | # TAG: includesource 19 | # 20 | # With this tag you can define which are the sources which hold 21 | # the files to backup. 22 | # 23 | # You can define each source on it's own line. Each source must 24 | # be followed by a pipe character and an alias. 25 | # 26 | # includesource=|alias= 27 | # 28 | # The goal of the alias is to provide a Junction label for the 29 | # targeted source and, also, to provide a meaningful container 30 | # name within the resulting compressed backup archive. 31 | # 32 | # You can set as many sources as you want one per line 33 | # There must be at least one 34 | # 35 | # Example 36 | # includesource=C:\Dir1|alias=Container1 37 | # includesource=C:\Dir2\Subdir1|alias=Container2 38 | # includesource=D:\Company\Documents|alias=Public 39 | # includesource=\\someserver\somesharedfolder|alias=Remote (see note !!) 40 | # 41 | # NOTE ! From version 1.8.0 of 7zbackup you can also specify 42 | # UNC paths as sources for your backup but this is possible 43 | # only if the script is ran on a Windows Vista / 7 / 2008 44 | # computer. 45 | # 46 | # Warning !! 47 | # Do not specify sources that are already below a previously 48 | # specified source as it will double backup your data. 49 | # 50 | # Example 51 | # includesource=C:\Dir1|alias=Container1 52 | # includesource=C:\Dir1\Subdir1|alias=Container2 <- WRONG !!! 53 | # 54 | # Default 55 | # includesource= 56 | 57 | # ******************************************************************** 58 | # TAG: emptydirs (optional) 59 | # 60 | # Specifies wether or not archive empty dirs too 61 | # Empty dirs are not really archived. The script drops a dummy file 62 | # into empty dirs to have it archived. After archiving dummy file 63 | # is immediately removed. 64 | # 65 | # This is a switch tag which means no value is associated 66 | # to it. 67 | # If you uncomment this tag the scan process will not 68 | # include empty dirs 69 | # 70 | # Default 71 | # emptydirs 72 | 73 | # ******************************************************************** 74 | # TAG: matchincludefiles (optional) 75 | # 76 | # Holds the regular expression to test file names against. 77 | # Every file name (regardless their path) which match this 78 | # regular expression will be selected and included in the backup 79 | # 80 | # If you do not specify any matchincludefiles directive then 81 | # the script will automatically select ALL files with respect 82 | # to the MAIN include criteria which is the type of backup. 83 | # 84 | # If you do specify a matchincludefile directive then only 85 | # filenames matching this expression will be selected. 86 | # 87 | # You can set as many sources as you want one per line 88 | # 89 | # Example to backup only *.pst files 90 | # matchincludefiles=.*\.pst$ 91 | # 92 | # Example to backup only *.pst files AND *.txt files 93 | # matchincludefiles=.*\.pst$|.*\.txt$ 94 | # 95 | # - OR - 96 | # matchincludefiles=.*\.pst$ 97 | # matchincludefiles=.*\.txt$ 98 | # 99 | # Default (all files are eligible for backup) 100 | # matchincludefiles= 101 | 102 | # ******************************************************************** 103 | # TAG: matchexcludepath (optional) 104 | # 105 | # By design behavior 7backup will recurse all subdirectories 106 | # for any given source. 107 | # This may cause you to backup some "unwanted" directory which 108 | # reside below the given source. 109 | # 110 | # With this regular expression you can specify which paths have 111 | # to be skipped. 112 | # 113 | # Imagine you have set D:\Dir1 as source and this directory 114 | # holds severals subdirs like this 115 | # D:\Dir1 == aliased as "Container1" 116 | # \Dir1.1 117 | # \Dir1.2 118 | # \Dir1.3 119 | # \Dir1.3.1 120 | # \Dir1.4 121 | # 122 | # and you do not want to backup Dir1.3 you can specify a regular 123 | # expression like this: 124 | # 125 | # matchexcludepath=^Container1\\Dir1\.3 126 | # 127 | # This wont stop the digging to further subfolders but obviuosly 128 | # every subfolder path will match the expression. 129 | # On the other hand if you want to skip the backup of folder 130 | # Dir1.3 ONLY and want to let the selection process to go further 131 | # deep in the directory tree (that means also Dir1.3.1 will be 132 | # scanned) you can change your regexp like this: 133 | # 134 | # matchexcludepath=^Container1\\Dir1\.3$ 135 | # 136 | # Please note that in this tag, if you want to refer to the parent 137 | # root of a directory you have to address the "alias" value of the 138 | # the source. 139 | # 140 | # You can set as many directives as you want one per line. 141 | # Take always care each line DOES NOT END WITH A "|" (pipe) 142 | # 143 | # Example 144 | # matchexcludepath=^Container1\\Dir1\.3$ 145 | # matchexcludepath=^Container1\\Dir1\.4 146 | # 147 | 148 | # ******************************************************************** 149 | # TAG: matchexcludefiles (optional) 150 | # 151 | # Holds the regular expression to test file names against. 152 | # Every file name (regardless their path) which match this 153 | # regular expression will be excluded from the selection criteria 154 | # 155 | # If you do not want to exclude any file upon regex criteria then 156 | # simply comment this line out. 157 | # 158 | # Example 159 | # matchexcludefiles=.*\.txt$ (to discard *.txt) 160 | # matchexcludefiles=.*\.txt$|.*\.tmp$ (to discard *.txt AND *.tmp) 161 | # 162 | # Default 163 | # matchexcludefiles=thumbs\.db$|.*\.mp3$|.*\~$|.*\.tmp$ 164 | 165 | matchexcludefiles=thumbs\.db$|.*\.mp3$|.*\~$|.*\.tmp$ 166 | 167 | # ******************************************************************** 168 | # TAG: matchcleanupdirs (optional) 169 | # 170 | # Holds the regular expression to test directory names against. 171 | # Every directory name (regardless their path) which match this 172 | # regular expression will be deleted during the 173 | # scanning/selection process. 174 | # 175 | # USE WITH GREAT CARE OR YOU WILL LIKELY HAVE ALL OF YOUR 176 | # IMPORTANT DATA SIMPLY NUCLEARIZED FROM YOUR SOURCES 177 | # DIRECTORIES MARKED AS JUNCTION POINTS WILL BE SIMPLY SKIPPED 178 | # 179 | # Example 180 | # matchcleanupdirs=.*\\veryunusefuldirectory$ 181 | 182 | # ******************************************************************** 183 | # TAG: matchcleanupfiles (optional) 184 | # 185 | # Holds the regular expression to test file names against. 186 | # Every file name (regardless their path) which match this 187 | # regular expression will be removed from source during the 188 | # scanning/selection process. 189 | # 190 | # USE WITH GREAT CARE OR YOU WILL LIKELY HAVE ALL OF YOUR 191 | # IMPORTANT DATA SIMPLY NUCLEARIZED FROM YOUR SOURCES 192 | # 193 | # Example 194 | # matchcleanupfiles=.*\.tmp$ (to delete *.tmp) 195 | 196 | # ******************************************************************** 197 | # TAG: maxfileage (optional) 198 | # 199 | # Expresses the maxage, in days, a file must have to be selected. 200 | # Calculation of age is made over LastWriteTime property compared 201 | # to the date the script started. 202 | # 203 | # By default this directive is commented out so no date criteria 204 | # is applied on file selection 205 | # 206 | # Example : to select files which have changed in the last 10 days 207 | # maxfileage=10 208 | # 209 | # Note this value supports decimal 210 | # maxfileage=1.5 means files with an age less than 36 hours 211 | # 212 | # Default 213 | # maxfileage=0 214 | 215 | # ******************************************************************** 216 | # TAG: minfileage (optional) 217 | # 218 | # Expresses the minage, in days, a file must have to be selected. 219 | # Calculation of age is made over LastWriteTime property compared 220 | # to the date the script started. 221 | # 222 | # By default this directive is commented out so no date criteria 223 | # is applied on file selection 224 | # 225 | # Example : to select files which have over than 10 days ago 226 | # minfileage=10 227 | # 228 | # Note this value supports decimal 229 | # maxfileage=1.5 means files with an age more than 36 hours 230 | # 231 | # Default 232 | # minfileage=0 233 | 234 | # ******************************************************************** 235 | # TAG: maxfilesize (optional) 236 | # 237 | # Expresses the maxfilesize, in bytes, a file must be to be selected. 238 | # 239 | # By default this directive is commented out so no date criteria 240 | # is applied on file selection. Be careful in selecting files 241 | # of size 0 242 | # 243 | # Example : to select files which are of size 1MB or lower 244 | # as 1MB = 1024Kb = 1024^2 Bytes 245 | # maxfilesize=1048576 246 | # 247 | # Default 248 | # maxfilesize= 249 | 250 | # ******************************************************************** 251 | # TAG: minfilesize (optional) 252 | # 253 | # Expresses the minfilesize, in bytes, a file must be to be selected. 254 | # 255 | # By default this directive is commented out so no date criteria 256 | # is applied on file selection. Be careful in selecting files 257 | # of size 0 258 | # 259 | # Example : to select files which are of size at least 1MB or higher 260 | # as 1MB = 1024Kb = 1024^2 Bytes 261 | # minfilesize=1048576 262 | # 263 | # Default 264 | # minfilesize= 265 | 266 | # ******************************************************************** 267 | # TAG: matchstoprecurse (optional) 268 | # 269 | # Holds the regular expression to test directory names against. 270 | # Every directory name (full path from Container) which match 271 | # this regular expression wont be entered for recursion. 272 | # In other words recursion into subdirectories will stop 273 | # if the path to be entered matches this regular expression. 274 | # 275 | # Example 276 | # matchstoprecurse=^Container1\\Dir1\.3 (will NOT enter Container1\Dir1.3) 277 | # matchstoprecurse=\\DirName (will NOT enter any directory named "DirName") 278 | # 279 | # Default 280 | # matchstoprecurse= 281 | 282 | # ******************************************************************** 283 | # TAG: maxdepth (optional) 284 | # 285 | # Expresses the maximum recursion level to be reached while 286 | # performing a scan on the directory tree in search of files 287 | # to backup. 288 | # 289 | # If not defined the script assumes a maximum level of 100 (default). 290 | # The value is zero-based which means a value of zero whil stop the 291 | # the scanning at the first level. A value of 1 will allow 1 recursion 292 | # level therefore scanning the firs level of subfolders and so on 293 | # 294 | # Example 295 | # maxdepth=100 (default) 296 | # maxdepth=3 297 | # 298 | # Default 299 | # maxdepth= 300 | 301 | # ******************************************************************** 302 | # TAG: rotate (optional) 303 | # 304 | # This variable holds the number of historycal archive backups you 305 | # want to keep on target media. An zero value means no rotation 306 | # will be performed after succesful archiving and YOU will be in charge 307 | # to delete old backups. Pay attention or your target media 308 | # will run out of free space soon. 309 | # For example: if you set this value to 3 then it means the 3 newest 310 | # backups of the current type are kept on target media. 311 | # For a "classic" 3 week incremental scheme we suggest to : 312 | # rotate=3 for full backups (launched once a week) 313 | # rotate=21 for incr backups (launched once per day) 314 | # 315 | # Example 316 | # rotate=5 317 | # 318 | # Default 319 | # rotate= 320 | 321 | # ******************************************************************** 322 | # TAG: nofollowjunctions (optional) 323 | # 324 | # This is a switch tag which means no value is associated 325 | # to it. 326 | # If you uncomment this tag the scan process will not 327 | # follow junction points: if a junction point is met the 328 | # scan process will not drop in. 329 | # 330 | # If this value is commented out then junction points will 331 | # be followed as normal directories. 332 | # 333 | # Default 334 | # nofollowjunctions 335 | 336 | # ******************************************************************** 337 | # TAG: compression (optional) 338 | # 339 | # This value holds the level of compression you want to reach 340 | # Permitted values are 1 or 3 or 5 or 7 or 9 341 | # 342 | # If omitted or not set then 7-zip will auto set it 343 | # 344 | # Example 345 | # compression=0 (no compression only archiving) 346 | # compression=1 (max speed low compression) 347 | # compression=9 (max compression low speed) 348 | # 349 | # Default 350 | # compression= 351 | 352 | # ******************************************************************** 353 | # TAG: threads (optional) 354 | # 355 | # Sets how many threads 7-zip is allowed to use. 356 | # By default 7-zip will endorse multithreading adopting 1 thread 357 | # per each available CPU core. 358 | # If you want to disable or control this behavior please set this 359 | # value. 360 | # 361 | # Example 362 | # threads=0 (multithreading disabled) 363 | # threads=1 (multithreading disabled) 364 | # threads=4 (use 4 threads on a 4+ core cpu) 365 | # 366 | # Default 367 | # which means use all available threads 368 | 369 | # ******************************************************************** 370 | # TAG: solid (optional) 371 | # 372 | # This value sets wether or not archive should endorse 373 | # solid mode. To understand what is the meaning of solid mode 374 | # please refer to 7-zip documentation 375 | # If this directive is not set and the format of the archive is 376 | # 7z then it's assumed solid mode should be endorsed 377 | # 378 | # Example 379 | # solid=0 (solid mode disabled) 380 | # solid=1 (solid mode enabled) 381 | # 382 | # Default 383 | # which meanse solid mode enabled 384 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Project Description 2 | 7zBackup is a PowerShell script aimed to help you automate your backup on-file tasks. 7zbackup leverages the great compression performances offered by 7-Zip while offering the great option to have different file sources stored in a single compressed archive. 3 | 4 | # Abstract 5 | Backup, Backup and again Backup. How many times have you heard this ? A good backup strategy is vital for any IT Infrastructure regardless their dimensions. Off-site backups are, without any doubt, the corner stone of those strategies but nowadays, the increased availability of on-disk space (larger disks, NAS, SANs), is a great help if you want to increase your backup frequencies using on-line attached media. 6 | That's why, in my personal experience, I make intensive usage of the "old pal" NtBackup to keep on disk different copies of Full/Incremental/Differential backups of my data and, of course, data from my customers. But while NtBackup is a good companion it lacks in one particular aspect: it waste a huge amount of bytes. Every .bkf file is plus the sum of all the data backed up. 7 | So ... if you have space ... why waste space ? There comes in mind the obvious answer: use compression. 8 | There are a lot of compression tools out there but none of them have succeded in my very personal expectations, till I found 7-Zip: it's free, it's small, it's fast, it's effective. 9 | There are a few drawbacks though: mainly the unability by 7zip to select files on specific criteria and to bind several sources in one archive unless you do it manually (many have encountered the "Duplicated File Name" problem). 10 | So I decided to write this small script which acts, substantially, as a selection wrapper for 7zip. 11 | 12 | ## What 7zbackup.ps1 IS 13 | It allows you to select files to backup using mostly the criteria of their "Archive" attribute which helps in building up catalogs to backup for Full, Differential and Incremental strategy. In addition it extends the selection criteria with several directives. You can fine tune the directories to dig into and file types/names to include or exclude. 14 | It prepares a list of files from which 7-Zip reads which files are to insert into archive 15 | It resolves the oddity of "Duplicate File Name" of 7Zip: with the proper usage of Junction points on NTFS file system the whole selection stays under one single root and all files in the list catalog report a relative path. It resets "Archive" attribute of archived files only if they're properly processed. This is relevant if you backup using differential and or incremental methods. It keeps your backup archives in order eliminating the "older" ones. 16 | It can help you cleaning up your directory structure from unwanted files ... in few words a small and free backup on-file solution. 17 | 18 | ## What 7zbackup.ps1 IS NOT and what it can't do 19 | * It's NOT a disaster recovery tool. 20 | * It can't save the state of your running machine. 21 | * It can't save ACLs of files into archives 22 | * It can't perform any restore operation. If you need to restore any file simply use 7-zip File Manager to open the generated archive and extract files you need. 23 | * It can't replace any of your off-site backup strategies. 24 | 25 | ## Please read. Please ... 26 | **This script makes use of Junction points (or Symbolic Links for Windows Vista/7/2008) typically placed in C: drive (root). These NTFS objects are displayed as folders in your Explorer interface. If, for any reason, the script should interrupt abnormally, it's generated junction points or symbolic links, may remain on disk. DO NOT USE WINDOWS EXPLORER TO DELETE JUNCTIONS OR SYMBOLIC LINKS AS IT TRAVERSES THE LINK AND MAY REMOVE YOUR REAL FILES AND FOLDERS.** 27 | 28 | * To remove a junction point use junction.exe with the -d switch. 29 | * To remove a symbolic link use the RD command line. If you are using Powershell, be more careful and use `cmd /c rmdir .\thesymlink'sname`. 30 | 31 | ## System Requirements 32 | * Windows XP, Windows Vista or better, Windows 2003 or better. (Might also work on Windows 2000 but there is some work to do for having PowerShell running on that platform) 33 | * NTFS File System 34 | * [PowerShell] 2.0 or better 35 | * [7-Zip] 9.2.0 or newest 36 | * [SysInternals] Junction Tool v. 1.0.5 ( not required if running Windows Vista / 7 / 2008) 37 | 38 | ## Features 39 | * Backup your files in compressed archives by 7-zip (7z format or zip or tar) 40 | * Full, Differential, Incremental and Copy Backups 41 | * Option to move files into archives (deleting original) 42 | * Flexible selection of files and paths using regular expressions 43 | * Flexible adjustement of compression over speed (compression level and threads) 44 | * Automatic removal of "old" backup archives (rotation) 45 | * Can remove unwanted files during the scan process 46 | * Can remove unwanted directories during the scan process 47 | * Send log of operations via email also to Cc and Bcc 48 | * Easily manageable like a script is 49 | * Easily schedule your backup operations (using task scheduler) 50 | 51 | [//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax) 52 | 53 | [PowerShell]: 54 | [7-Zip]: 55 | [SysInternals]: 56 | 57 | 58 | --------------------------------------------------------------------------------