Skip to content

Instantly share code, notes, and snippets.

@hkarthik7
Last active September 8, 2020 08:49
Show Gist options
  • Save hkarthik7/15b423fbff84c91adc40b380e7df1796 to your computer and use it in GitHub Desktop.
Save hkarthik7/15b423fbff84c91adc40b380e7df1796 to your computer and use it in GitHub Desktop.
Export and Import automation of Azure Sql database
# Set-PSDBDefaults can be used to set the subscription in current context and allows you to set the function
# default parameters such as resource group name, server name and database name
#region Export database
Set-PSDBDefaults -Subscription "mySubscription01"
$password = Get-PSDBKVSecret -VaultName "kv-01" -SecretName "sqlpassword"
$exportParams = @{
ResourceGroupName = "myRSG"
ServerName = "sqlserver01"
DatabaseName = "database01"
StorageAccountName = "backups"
StorageContainerName = "sqlbackups"
AdministratorLogin = "sqladmin"
AdministratorLoginPassword = $password
Subscription = "mySubscription02"
}
$export = Export-PSDBSqlDatabase @exportParams
Write-Output "Status is: $(Get-PSDBImportExportStatus -StatusLink $export)"
## Now that the script has to pause and check the status of export operation till it completes and
## move on to next function once the status is successful.
## by default the Get-PSDBImportExportStatus waits for 5 minutes and checks the status for every 5 seconds.
Get-PSDBImportExportStatus -StatusLink $export -Wait
#endregion Export database
#region import database
$importParams = @{
ResourceGroupName = "myRSG02"
ServerName = "sqlserver02"
DatabaseName = "database02"
StorageAccountName = "backups"
StorageContainerName = "sqlbackups"
AdministratorLogin = "databaseadmin01"
AdministratorLoginPassword = ("databasepassword" | ConvertTo-SecureString -AsPlainText -Force)
}
$import = Import-PSDBSqlDatabase @importParams
Write-Output "Status is: $(Get-PSDBImportExportStatus -StatusLink $import)"
# now that the script has to wait till the import completes
Get-PSDBImportExportStatus -StatusLink $import -Wait
#endregion import database
## Once done you can use function Get-PSDBDatabaseData or Invoke-PSDBDatabaseQuery to run some queries on the targer or copied database
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment