Wednesday, May 27, 2020

PowerShell Script | Backup Azure SQL MI DB to Blob

#Install-Module dbatools
#Install-Module -Name Az -AllowClobber -Scope AllUsers


param(
[string]$server = ".", 
[string] $Database ,
[string] $subscription,
[string] $ResourceGroupName,
[string] $StorageAccount,
[string] $container,
[string] $BackupfileName = "1"
)
#Get-AzSubscription | Format-Table
#Set-AzContext "Rizwan_Internal_1000"
#$subscription = 'Rizwan_Internal_1000'
Select-AzSubscription -Subscription $subscription
Get-AzContext
#$server = "tcp:sql1243.public.b955f902d673.database.windows.net,3342"
#$Database = "Pubs"
$server_Login = (Get-Credential)

#Setting up backup file name
if ($BackupfileName -ne "1")
{
    $BackupfileName = $BackupfileName
}
else {
    $dt = Get-Date -Format yyyyMMdd_HHmmss
    $BackupfileName = $Database + "_$dt" + ".bak"
}

$BlobStorageURL = "https://$StorageAccount.blob.core.windows.net/$container"
Write-Host $BlobStorageURL, $Server, $Database, $subscription

$StorageAccount = Get-AzStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccount
$ctx = $storageAccount.Context


#checking if credential already exist or need be created
$SASCredential = Get-DbaCredential -SqlInstance $server -SqlCredential $server_Login 
$SQLMI = Connect-DbaInstance -SqlInstance $server -SqlCredential $server_Login

$sas = (New-AzStorageAccountSASToken -Service Blob -ResourceType Object -Permission "rwdl" -Context $ctx).TrimStart('?')
$serverCred = New-DbaCredential -SqlInstance $SQLMI `
                       -Name $BlobStorageURL `
                       -Identity "SHARED ACCESS SIGNATURE" `
                       -SecurePassword (ConvertTo-SecureString $sas -AsPlainText -Force) `
                       -Force
write-host "Credential recreated"
<#
if ($SASCredential.Name -eq $BlobStorageURL)
{
     
    write-host "Credential already exists, skipping this step"
}
Else {
    $sas = (New-AzStorageAccountSASToken -Service Blob -ResourceType Object -Permission "rwdl" -Context $ctx).TrimStart('?')
    $serverCred = New-DbaCredential -SqlInstance $SQLMI `
                           -Name $BlobStorageURL `
                           -Identity "SHARED ACCESS SIGNATURE" `
                           -SecurePassword (ConvertTo-SecureString $sas -AsPlainText -Force) `
                           -Force
                           
    write-host "Credential does NOT and it has been created"
}
#>
Backup-DbaDatabase -SqlInstance $SQLMI -Database $Database `
    -AzureBaseUrl $BlobStorageURL `
    -BackupFileName $BackupfileName `
    -Type Full -Checksum -CopyOnly -CompressBackup -Verbose
x

Powershell Script to Refresh Azure SQL DB from one server to another within same subscription

This script will allow you to refresh Azure SQL DB from one server to another within the same subscription. It renames target server before restoring and also matches service level of target database.



<#
Azure PowerShell Module Installation is required
if (Get-Module -Name AzureRM -ListAvailable) {
    Write-Warning -Message 'Az module not installed. Having both the AzureRM and Az modules installed at the same time is not supported.'
} else {
    Install-Module -Name Az -AllowClobber -Scope CurrentUser
}
https://docs.microsoft.com/en-us/powershell/azure/install-az-ps?view=azps-4.1.0
#>

#Connect to Azure if not already connected
Connect-AzAccount
#Get information which subscriptin you are connected in
Get-AzContext
#Set subscription in which source and target SQL are located
Get-AzSubscription
Set-AzContext '<Set Subscription>'
#Variables
$S_ResourceGroup = '<Source Resource Group>'
$S_Server = '<Source Server>'
$Database = '<DB to be refreshed>'


$T_ResourceGroup = '<Target Resource Group>'
$T_Server = '<Target Server>'
$T_OriginalName = '<Target DB Original Name>'
$dt = Get-Date -Format yyyyMMdd
$T_DBOriginalRename = $T_OriginalName +'_' +$dt





#Get Target DB Service Level
$T_DB = Get-AzSqlDatabase -ResourceGroupName $T_ResourceGroup -ServerName $T_Server -DatabaseName $T_OriginalName
#Rename TargetDatabse to be refreshed
Set-AzSqlDatabase -ResourceGroupName $T_ResourceGroup -ServerName $T_Server -DatabaseName $T_OriginalName -NewName $T_DBOriginalRename
#Start copy of the sourceDB to TargetDB
New-AzSqlDatabaseCopy -ResourceGroupName $S_ResourceGroup -ServerName $S_Server -DatabaseName $Database -CopyResourceGroupName $T_ResourceGroup -CopyServerName $T_Server -CopyDatabaseName $Database
Get-AzSqlDatabase -ResourceGroupName $T_ResourceGroup -ServerName $T_Server -DatabaseName $Database
Start-Sleep -Seconds 10
#Set Restored DB Service Tier
Set-AzSqlDatabase -ResourceGroupName $T_ResourceGroup -ServerName $T_Server -DatabaseName $Database -Edition $T_DB.Edition -RequestedServiceObjectiveName $T_DB.CurrentServiceObjectiveName
<#
REsources
https://docs.microsoft.com/en-us/powershell/module/az.sql/set-azsqldatabase?view=azps-4.1.0
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-copy?tabs=azure-powershell
https://docs.microsoft.com/en-us/azure/sql-database/scripts/sql-database-copy-database-to-new-server-powershell
https://docs.microsoft.com/en-us/azure/sql-database/sql-database-single-databases-manage#powershell-manage-sql-database-servers-and-single-databases
Get-AzSqlServerServiceObjective -Location 'EastUS2' | Out-GridView
#>