#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
I am a passionate SQL DBA and like to learn more about it everyday. Also I am interested in learning about tools that make our lives easier and business processes that help DBA's become business partners as compared to just technical leads.
Wednesday, May 27, 2020
PowerShell Script | Backup Azure SQL MI DB to Blob
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment