Guest User

Untitled

a guest
Dec 17th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. ## Stop SqlServer Manager ###
  2.  
  3. Stop-Process -Name ssms -Force
  4.  
  5. ##### Delete File ##########
  6.  
  7. $limit = (Get-Date).AddMinutes(-60)
  8. $path="C:ProgramFilesMicrosoftSQLServerMSSQL14.MSSQLSERVERMSSQLBackup"
  9. $Extension = "*."
  10.  
  11. # Delete files older than the $limit.
  12. Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
  13.  
  14. ##### File Download ##########
  15.  
  16. $localPath = "C:Program FilesMicrosoft SQLServerMSSQL14.MSSQLSERVERMSSQLBackup"
  17. $remotePath = "/production/"
  18.  
  19. try
  20. {
  21. # Load WinSCP .NET assembly
  22. Add-Type -Path "C:Program Files (x86)WinSCPWinSCPnet.dll"
  23.  
  24. # Set up session options
  25. $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
  26. Protocol = [WinSCP.Protocol]::Sftp
  27. HostName = "sftpserver@hosting.com"
  28. UserName = "redacted"
  29. Password = "redacted"
  30. SshHostKeyFingerprint = "redacted"
  31. }
  32.  
  33. $session = New-Object WinSCP.Session
  34.  
  35. $session = New-Object WinSCP.Session
  36.  
  37. try
  38. {
  39. # Connect
  40. $session.Open($sessionOptions)
  41.  
  42. # Get list of files in the directory
  43. $directoryInfo = $session.ListDirectory($remotePath)
  44.  
  45. # Select the most recent file
  46. $latest =
  47. $directoryInfo.Files |
  48. Where-Object { -Not $_.IsDirectory } |
  49. Sort-Object LastWriteTime -Descending |
  50. Select-Object -First 1
  51.  
  52. # Any file at all?
  53. if ($latest -eq $Null)
  54. {
  55. Write-Host "No file found"
  56. exit 1
  57. }
  58.  
  59. # Download the selected file
  60. $session.GetFiles(
  61. [WinSCP.RemotePath]::EscapeFileMask($latest.FullName), $localPath).Check()
  62. }
  63. finally
  64. {
  65. # Disconnect, clean up
  66. $session.Dispose()
  67. }
  68.  
  69. exit 0
  70. }
  71. catch
  72. {
  73. Write-Host "Error: $($_.Exception.Message)"
  74. exit 1
  75. }
  76.  
  77. ##### Restore Database ######
  78.  
  79. $FileName = Get-ChildItem -path $path
  80.  
  81.  
  82. Restore-SqlDatabase -ServerInstance "MACHINEINSTANCE" -Database "DB_Prod" -BackupFile $FileName -ReplaceDatabase
Add Comment
Please, Sign In to add comment