backup_to_server.psm1 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. # Custom backup script
  2. function backup_to_server {
  3. param(
  4. [switch]$skipappdir,
  5. [switch]$noupload,
  6. [switch]$skipoutlook)
  7. . (Join-Path $PSScriptRoot handle_exclude_lists.ps1)
  8. # Backup folder
  9. $backup_dir = "$HOME"
  10. if (!(Test-Path $backup_dir) ) { mkdir $backup_dir }
  11. # Make sure we have an authentication key
  12. $key_file = "$HOME\.ssh\bethany_putty.ppk"
  13. if (!(Test-Path $key_file) ) { write-host "Unable to find a key for connecting to the server"; return }
  14. # Setup to use 7zip and add WinSCP to the path
  15. $env:Path += ";C:\Program Files\7-Zip;C:\Program Files (x86)\WinSCP"
  16. if (! (Test-Path 'C:\Program Files\7-Zip\7z.exe')) {
  17. Write-Error "Unable to locate 7-zip program file"
  18. exit 1
  19. }
  20. Set-Alias sz 'C:\Program Files\7-Zip\7z.exe'
  21. # Create a compressed version of the App Dir
  22. if (!($skipappdir)) {
  23. # Create the main backup file
  24. $backup_file = "$backup_dir\appdir.7z"
  25. # Make sure we start in the home folder
  26. Set-Location $HOME
  27. # Remove the previous file (start clean each time)
  28. if (Test-Path $backup_file) { Remove-Item $backup_file }
  29. # Load the exclude list
  30. $exclude = parse_appdata_exclude
  31. # Generate the compressed backup
  32. Invoke-Command -ScriptBlock { sz a -bb0 -t7z $args[0] $args[1] "$HOME\AppData"
  33. } -ArgumentList @($exclude, $backup_file)
  34. }
  35. if (!($noupload)) {
  36. # Create a timestamp file to confirm when the last backup was done
  37. Set-Content -Value (Get-Date) -Path ("$backup_dir\updated.txt")
  38. Set-Location $HOME
  39. # Config file
  40. $config_file = Join-Path $env:TEMP backup_script.txt
  41. Set-Content $config_file "open sftp://bethany@thorin/ -hostkey=""ssh-ed25519 256 1d0dZTuF/AnK1iGlgjJnT2WEqcpJ6mGKQ4G8A9klmRA"" -privatekey=""$key_file"""
  42. Add-Content $config_file "option batch continue"
  43. # Sync to server
  44. $remote_directory = "/data/backups/bethany/{0}/Profiles/" -f ( $env:COMPUTERNAME )
  45. $local_directory = "c:\Users"
  46. $mask = parse_sync_exclude
  47. $config = "synchronize remote -delete -filemask=""$mask"" ""$local_directory"" $remote_directory"
  48. Add-Content $config_file "$config"
  49. # If requested, sync the outlook data files as well
  50. if (!($skipoutlook)) {
  51. $local = "$HOME\AppData\Local\Microsoft\Outlook\*.ost"
  52. $remote = "/data/backups/bethany/{0}/" -f $env:COMPUTERNAME
  53. $config = "put -resume ""$local"" $remote"
  54. Add-Content $config_file $config
  55. }
  56. # Complete the config file and execute
  57. Add-Content $config_file "exit"
  58. WinSCP.com /script=$config_file
  59. }
  60. }
  61. Export-ModuleMember backup_to_server