Advertisement
robbinespu

mssql database backup (sort by size and copy the smaller one first)

Jan 26th, 2024
1,095
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PowerShell 1.67 KB | Source Code | 0 0
  1. # Database name
  2. $databaseName = "MY-DATABASE-HERE"
  3.  
  4. # Source and destination folders
  5. $sourceFolder = "D:\Database\Data"
  6. $destinationFolder = "F:\Database\Data"
  7.  
  8. # Check if the source folder exists
  9. if (Test-Path $sourceFolder -PathType Container) {
  10.  
  11.     # Create the destination folder if it doesn't exist
  12.     if (-not (Test-Path $destinationFolder -PathType Container)) {
  13.         New-Item -ItemType Directory -Force -Path $destinationFolder
  14.     }
  15.  
  16.     # Get all files in the source folder and filter based on the database name
  17.     $sourceDataFiles = Get-ChildItem -Path $sourceFolder | Where-Object { $_.Name -like "$databaseName*.ndf" -or $_.Name -like "$databaseName*.mdf" } |
  18.                       Sort-Object -Property Length
  19.  
  20.     # Build paths for the source and destination data files
  21.     $destinationDataFiles = $sourceDataFiles | ForEach-Object { Join-Path -Path $destinationFolder -ChildPath $_.Name }
  22.  
  23.     $totalFiles = $sourceDataFiles.Count
  24.     $completedFiles = 0
  25.  
  26.     # Copy the data files with progress information
  27.     foreach ($file in $sourceDataFiles) {
  28.         $destinationPath = Join-Path -Path $destinationFolder -ChildPath $file.Name
  29.         Write-Host "Copying $($file.FullName) to $($destinationPath)..."
  30.         Copy-Item -Path $file.FullName -Destination $destinationPath -Force
  31.         $completedFiles++
  32.         $copyPercentage = ($completedFiles / $totalFiles) * 100
  33.         Write-Host "File copied. Progress: $($completedFiles) of $($totalFiles) files copied. Copy percentage: $($copyPercentage)%`n"
  34.     }
  35.  
  36.     Write-Host "Database files for $databaseName copied successfully."
  37.  
  38. } else {
  39.     Write-Host "Source folder does not exist."
  40. }
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement