Restoring database .BAK file in Azure SQL Managed instance with PowerShell module dbatools

 

The script will not RESTORE the database, it will generate script for RESTORE and we can copy and paste it in SSMS.
cls
$Username = 'UserNameHere'
$Password = ConvertTo-SecureString -String 'Password' -AsPlainText -Force
$Creds = New-Object `
 -TypeName System.Management.Automation.PSCredential($Username,$Password)
Get-DbaDatabase `
  -sqlinstance 'managedInstanceNameHere.database.windows.net' `
  -SqlCredential $Creds
<#
   The value that we have provided for -Path parameter is need to taken
   from teh .bak file properties url not from container and storage.
#>
Restore-DbaDatabase `
 -SqlInstance 'managedInstanceNameHere.database.windows.net' `
 -SqlCredential $Creds `
 -DatabaseName TEST `
 -Path 'Take the backp file(.bak) path properties URL ' `
 -OutputScriptOnly `
 -Verbose
PowerShell Script
$Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size(300, 5000)
cls
$DBs = 'dbname'

$DBs | foreach {
    $DB = $_
    ''
    "/*========= Database Name : $($DB) ============*/"
    ''

    $path = -join('\\a\\SQL-Backups\\b\\c\\', $($DB), '\\*.*')

    $FullName = (
        Get-ChildItem -Recurse -Path $path |
        Where-Object {
            $_.Name -match '.' -and
            $_.LastWriteTime -gt '11/20/2025 5:04 AM'
        }
    ).FullName

    foreach($file in $FullName) {
        if($file -match '.bak') {
            Write-Output "EXECUTE AS LOGIN ='SA'"
            Write-Output ""

            Write-Output @"
restore database [$($DB)]`r`nfrom disk ='$($file)'
with Norecovery, stats =2
"@

            Write-Output ""
        }
        else {
            Write-Output @"
restore log [$($DB)] `r`nfrom disk ='$($file)'
with Norecovery, stats =2
"@
        }
    }

    Write-Output ""

    Write-Output @"
ALTER DATABASE [$($DB)] 
SET HADR AVAILABILITY GROUP = [aggroupnamehere];
"@
}

Comments

Popular posts from this blog

Always On FailOver Events

The transaction log for database is full due to 'OLDEST_PAGE'

SSAS Cube or Database backup with Powershell command "Backup-AsDatabase"