Start-AzureSqlDatabaseExport Object Reference not set to an instance of an object - azure

I'm not sure how to debug this, assuming it's not a problem with the cmdlet. I'm trying to replace the automated SQL export with an automation workflow, but I can't seem to get Start-AzureSqlDatabaseExport to work -- it keeps getting the following warning and error messages.
d4fc0004-0c0b-443e-ad1b-310af7fd4e2a:[localhost]:Client Session Id: 'c12c92eb-acd5-424d-97dc-84c4e9c4f914-2017-01-04
19:00:23Z'
d4fc0004-0c0b-443e-ad1b-310af7fd4e2a:[localhost]:Client Request Id: 'd534f5fd-0fc0-4d68-8176-7508b35aa9d8-2017-01-04
19:00:33Z'
Start-AzureSqlDatabaseExport : Object reference not set to an instance of an object.
At DBBackup:11 char:11
+
+ CategoryInfo : NotSpecified: (:) [Start-AzureSqlDatabaseExport], NullReferenceException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.StartAzureSqlDatabaseExport
This seems similar to some other questions, but they seem to be unanswered or not applicable. I did have a similar procedure working in the Powershell environment. I replaced that procedure with the automated export from Azure, which seems like a poor choice now! I've tried a number of variations, using sqlcontext and databasename instead of database, for example.
Here's my code with sensitive parts replaced with ****:
workflow DBBackup {
param(
[parameter(Mandatory=$true)]
[string] $dbcode
)
$cred = Get-AutomationPSCredential -Name "admindbcredentials"
$VerbosePreference = "Continue"
inlineScript {
$dbcode = $using:dbcode
$cred = $using:cred
if ($dbcode -eq $null)
{
Write-Output "Database code must be specified"
}
Else
{
$dbcode = $dbcode.ToUpper()
$dbsize = 1
$dbrestorewait = 10
$dbserver = "kl8p7d444a"
$stacct = $dbcode.ToLower()
$stkey = "***storagekey***"
Write-Verbose "DB Server '$dbserver' DB Code '$dbcode'"
Write-Verbose "Storage Account '$stacct'"
$url = "https://$dbserver.database.windows.net"
$sqlctx = New-AzureSqlDatabaseServerContext -ManageUrl $url -Credential $cred
# $sqlctx = New-AzureSqlDatabaseServerContext -ManageUrl $url -Credential $cred
$stctx = New-AzureStorageContext -StorageAccountName $stacct -StorageAccountKey $stkey
$dbname = "FSUMS_" + $dbcode
$dt = Get-Date
$timestamp = $dt.ToString("yyyyMMdd") + "_" + $dt.ToString("HHmmss")
$bkupname = $dbname + "_" + $timestamp + ".bacpac"
$stcon = Get-AzureStorageContainer -Context $stctx -Name "backups"
$db = Get-AzureSqlDatabase -Context $sqlctx -DatabaseName $dbname
Write-Verbose "Backup $dbname to $bkupname in storage account $stacct"
Start-AzureSqlDatabaseExport $sqlctx -DatabaseName $dbname -StorageContainer $stcon -BlobName $bkupname
}
}
}

Try New-AzureRmSqlDatabaseExport instead. This command will return export status object. If you want a synchronous export you can check for "export status" in a loop.

Adding the following lines corrected the problem:
In the workflow before inlineScript:
$cred = Get-AutomationPSCredential -Name "admincredentials"
(where admincredentials was an asset with my admin login credentials)
and inside the inlineScript:
Add-AzureAccount $cred
Select-AzureSubscription "My subscription"
Some runbooks don't seem to need this, but probably best to always include it.

Related

How to set the ComputeModel property to Serverless on an Azure SQL Database using PowerShell?

I'm restoring an Azure SQL Database (Serverless) from a deleted database backup using Get-AzSqlDeletedDatabaseBackup and Restore-AzSqlDatabase PowerShell commandlets. The restore works, but the tags and ComputeModel are not restored with the database.
I've tried using Set-AzSqlDatabase:
Set-AzSqlDatabase -ResourceGroupName $resourcegroupname -DatabaseName $databasename -ServerName $servername -ComputeModel "Serverless" -AutoPauseDelayInMinutes 45
Update: I tried the following code and the Kind is set prior to using the Set-AzResource cmdlet, but it doesn't stick
$resource = Get-AzResource -ResourceGroupName $resourcegroupname -ResourceType "Microsoft.Sql/servers/databases" -Name "$servername/$databasename"
Write-Host "Setting ComputeModel to Serverless..."
$resource.Kind = "v12.0,user,vcore,serverless"
$resource
# resource.Kind is successfully set on the $resource object
Write-Host "Set-AzResource..."
$resource | Set-AzResource -Force
Anyone have any ideas?
Thank you.
Cheers,
Andy
The Get-AzSqlDeletedDatabaseBackup and Restore-AzSqlDatabase PowerShell cmdlets are doesn't contain a property to get the ComputeModel.
While Restore and Delete Backup database we don't require the ComputeModel properties. while setting database we need to require the ComputeModel.
If you want to get the compute model for the Azure SQL Database you can use, Get-AzResource command to fetch the specific information.
Thanks #joy wang SO Solution we can get the serverless Azure SQL Database.
Thanks to #holger and #Delliganesh Sevanesan for the help, I was able implement a solution that restores the most recent deleted database (SQL Database), adds some resource tags, and sets the ComputeModel to serverless.
Here's the code:
<#
Purpose: Restore the most recently deleted Azure Sql Database
Dependencies:
Az.Sql PowerShell module
#>
# Set variables first
$resourcegroupname = 'myresourcegroup'
$servername = 'myservername'
$databasename = 'mydatabasename'
[hashtable]$tags = #{
application = "testing"
}
try {
$deleteddatabases = Get-AzSqlDeletedDatabaseBackup -ResourceGroupName $resourcegroupname -ServerName $servername -DatabaseName $databasename
} catch {
Write-Error "Error getting database backups [Get-AzSqlDeletedDatabaseBackup]: " + $_.Exception.Message
exit(1)
}
# Get most recent backup in case there are multiple copies
# Assumes index and order in foreach is the same - proven in test
Write-Host "Database backups:"
$index = 0
$MostRecentBackupIndex = 0
$MostRecentBackupDate = (Get-date).AddDays(-2) # initialize variable with date from two days ago
foreach ($db in $deleteddatabases) {
if ($db.CreationDate -ge $MostRecentBackupDate) {
$MostRecentBackupIndex = $index
$MostRecentBackupDate = $db.CreationDate
Write-Host "Most Recent Database: $($db.DatabaseName) : Created: $($db.CreationDate) : DeleteDate: $($db.DeletionDate)"
}
$index++
}
$deleteddatabase = $deleteddatabases[$MostRecentBackupIndex]
Write-Host "----------------------------------------------------------------------------------"
Write-Host "Restoring: $($deleteddatabase.DatabaseName) from: $($deleteddatabase.CreationDate) backup"
Write-Host "----------------------------------------------------------------------------------"
Write-Host "Deleted database info ResourceId: "
Write-Host $deleteddatabase.ResourceId
try {
Restore-AzSqlDatabase -FromDeletedDatabaseBackup `
-DeletionDate $deleteddatabase.DeletionDate `
-ResourceGroupName $resourcegroupname `
-ServerName $servername `
-TargetDatabaseName $databasename `
-ResourceId $deleteddatabase.ResourceID `
-Edition $deleteddatabase.Edition `
-Vcore 2 `
-ComputeGeneration "Gen5"
} catch {
Write-Error "Error restoring database [Restore-AzSqlDatabase]: " + $_.Exception.Message
exit(1)
}
# Wait a few minutes to allow restore to complete before applying the tags
Start-Sleep -Seconds 180
Write-Host "Applying tags to database..."
try {
$resource = Get-AzResource -ResourceGroupName $resourcegroupname -ResourceType "Microsoft.Sql/servers/databases" -Name "$servername/$databasename"
New-AzTag -ResourceId $resource.Id -Tag $tags
} catch {
Write-Error "Error adding tags to database [Get-AzResource, New-AzTag]: " + $_.Exception.Message
exit(1)
}
Write-Host "Setting ComputeModel to Serverless..."
try {
# Important - must include -AutoPauseDelayInMinutes 60, -MinVcore, and MaxVcore parameters (thanks holger)
Set-AzSqlDatabase -ResourceGroupName $resourcegroupname -DatabaseName $databasename -ServerName $servername -ComputeModel Serverless -AutoPauseDelayInMinutes 60 -MinVcore 1 -MaxVcore 2
} catch {
Write-Error "Error setting serverless mode [Set-AzSqlDatabase]: " + $_.Exception.Message
exit(1)
}
Write-Host "Database restore complete."

Azure Automation Account - Runbook Error - Object reference not set to an instance of an object

Last week, I deployed a script to backup some disks using the New-AzSnapshot cmdlet.
I scheduled this script in the Azure Automation Account and for the first 2 days, the script worked very well!
Today, I analyzed the logs and saw that the script had the error below:
Connect-AzAccount : Object reference not set to an instance of an object. At line:12 char:25 + $connectionResult = Connect-AzAccount ` + ~~~~~~~~~~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Connect-AzAccount], NullReferenceException + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.ConnectAzureRmAccountCommand
Does anyone have any idea what may be causing this error?
Below the script:
Param(
[string]$resourceGroupName
)
$connection = Get-AutomationConnection -Name AzureRunAsConnection
while (!($connectionResult) -And ($logonAttempt -le 10)) {
$LogonAttempt++
# Logging in to Azure...
$connectionResult = Connect-AzAccount `
-ServicePrincipal `
-Tenant $connection.TenantID `
-ApplicationID $connection.ApplicationID `
-CertificateThumbprint $connection.CertificateThumbprint
Start-Sleep -Seconds 30
}
# Remove old snapshots
$snapshotnames = (Get-AzSnapshot -ResourceGroupName $resourceGroupName).name
foreach($snapname in $snapshotnames)
{
Get-AzSnapshot -ResourceGroupName $resourceGroupName -SnapshotName $snapname | ?{($_.TimeCreated) -lt ([datetime]::UtcNow.AddMinutes(-10080))} | Remove-AzSnapshot -Force
}
foreach ($VMs in Get-AzVM -ResourceGroupName $resourceGroupName) {
#Set local variables
$location = $VMs.Location
#$resourceGroupName = $vmInfo.ResourceGroupName
$timestamp = Get-Date -f MM-dd-yyyy_HH_mm_ss
#Snapshot name of OS data disk
$snapshotName = "bkp-" + $VMs.Name + "-" + $timestamp
#Create snapshot configuration
$snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.OsDisk.ManagedDisk.Id -Location $location -CreateOption copy
#Take snapshot
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName
if ($VMs.StorageProfile.DataDisks.Count -ge 1) {
#Condition with more than one data disks
for ($i = 0; $i -le $VMs.StorageProfile.DataDisks.Count - 1; $i++) {
#Snapshot name of OS data disk
$snapshotName = "bkp-" + $VMs.StorageProfile.DataDisks[$i].Name + "-" + $timestamp
#Create snapshot configuration
$snapshot = New-AzSnapshotConfig -SourceUri $VMs.StorageProfile.DataDisks[$i].ManagedDisk.Id -Location $location -CreateOption copy
#Take snapshot
New-AzSnapshot -Snapshot $snapshot -SnapshotName $snapshotName -ResourceGroupName $resourceGroupName
}
}
else {
Write-Host $VMs.Name + " doesn't have any additional data disk."
}
}
You're having a nullreference exception, looking at the location inside the error message (At line:12 char:25). it shows that connection is null.
You need to declare connection first on the same page before you're able to use the variables inside.
See also: What is a NullReferenceException, and how do I fix it?
EDIT: At second notice, I think that you're already declaring the $connection at
$connection = Get-AutomationConnection -Name AzureRunAsConnection
but it looks like that's returning null. In that case, you'll need to figure out why that's returning null, because it should return a filled $connection if connected.
For a safe check to avoid errors: you should check first if the $connection is not null before entering the while, (for example $connection != null could work for Javascript). That way you won't get errors, but keep in mind that you won't get a result through this.

Azure PowerShell script does not work when change to a different Azure Subscription

I am experiencing a very strange problem. I recently switched Azure subscription from free trial to pay-as-you-go. The PowerShell script i wrote to create Azure Resource Group, Azure Data Factory, Azure Active Directory App Azure SQL Server, Azure SQL Database does not work. below is the sample code from script and error messages
New-AzResourceGroup Test2ResourceGroupName2 -location 'westeurope'
$AzADAppName = "TestADApp1"
$AzADAppUri = "https://test.com/active-directory-app"
$AzADAppSecret = "TestSecret"
$AzADApp = Get-AzADApplication -DisplayName $AzADAppName
if (-not $AzADApp) {
if ($AzADApp.IdentifierUris -ne $AzADAppUri) {
$AzADApp = New-AzADApplication -DisplayName $AzADAppName -HomePage $AzADAppUri -IdentifierUris $AzADAppUri -Password $(ConvertTo-SecureString -String $AzADAppSecret -AsPlainText -Force)
}
}
New-AzResourceGroup : Your Azure credentials have not been set up or have expired, please run Connect-AzAccount to set up your Azure credentials.
At line:1 char:1
+ New-AzResourceGroup Test2ResourceGroupName2 -location 'westeurope'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzResourceGroup], ArgumentException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureResourceGroupCmdlet
Get-AzADApplication : User was not found.
At line:6 char:12
+ $AzADApp = Get-AzADApplication -DisplayName $AzADAppName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-AzADApplication], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.GetAzureADApplicationCommand
New-AzADApplication : User was not found.
At line:11 char:20
+ ... $AzADApp = New-AzADApplication -DisplayName $AzADAppName -HomePage $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-AzADApplication], Exception
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.ActiveDirectory.NewAzureADApplicationCommand
However if i execute this command in Azure Cloud Shell it works.
New-AzResourceGroup Test2ResourceGroupName -location 'westeurope'
I am also able to create Resource Group and other resources in Azure Portal. We cannot use portal and we have to use powershell due to company policy. could anyone help why PowerShell is not working
Here is the full script as requested in comments
Connect-AzAccount -TenantID xxxxx-xxx-xxx-xxxxx-xxxxx
# Creating Azure Active Directory App
$AzADAppName = "xxxxx-active-directory-app"
$AzADAppUri = "https://xxxxx.com/xxxxx-app"
$AzADAppSecret = "xxxxx"
$AzADApp = Get-AzADApplication -DisplayName $AzADAppName
if (-not $AzADApp) {
if ($AzADApp.IdentifierUris -ne $AzADAppUri) {
$AzADApp = New-AzADApplication -DisplayName $AzADAppName -HomePage $AzADAppUri -IdentifierUris $AzADAppUri -Password $(ConvertTo-SecureString -String $AzADAppSecret -AsPlainText -Force)
$AzADServicePrincipal = New-AzADServicePrincipal -ApplicationId $AzADApp.ApplicationId
# Assign the Contributor RBAC role to the service principal
# If you get a PrincipalNotFound error: wait 15 seconds, then rerun the following until successful
$Retries = 0; While ($NewRole -eq $null -and $Retries -le 6) {
# Sleep here for a few seconds to allow the service principal application to become active (usually, it will take only a couple of seconds)
Sleep 15
New-AzRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $AzADApp.ApplicationId -ErrorAction SilentlyContinue
$NewRole = Get-AzRoleAssignment -ServicePrincipalName $AzADServicePrincipal.ApplicationId -ErrorAction SilentlyContinue
$Retries++;
}
"Application {0} Created Successfully" -f $AzADApp.DisplayName
# Display the values for your application
"Save these values for using them in your application"
"Subscription ID: {0}" -f (Get-AzContext).Subscription.SubscriptionId
"Tenant ID:{0}" -f (Get-AzContext).Tenant.TenantId
"Application ID:{0}" -f $AzADApp.ApplicationId
"Application AzADAppSecret :{0}" -f $AzADAppSecret
}
}
else {
"Application{0} Already Exists" -f $AzADApp.DisplayName
}
# Creating Azure Resource Group
$DataFactoryName = "xxxxx-DataFactory"
$ResourceGroupName = "xxxxx-ResourceGroup"
$ResourceGroup = Get-AzResourceGroup -Name $ResourceGroupName
$Location = 'westeurope'
if (-not $ResourceGroup) {
$ResourceGroup = New-AzResourceGroup $ResourceGroupName -location 'westeurope'
if ($ResourceGroup) {
"Resource Group {0} Created Successfully" -f $ResourceGroup.ResourceGroupName
}
else {
"ERROR: Resource Group Creation UNSUCCESSFUL"
}
}
else {
"Resource Group {0} Exists" -f $ResourceGroup.ResourceGroupName
}
# Creating Azure Data Factory
$DataFactory = Get-AzDataFactoryV2 -Name $DataFactoryName -ResourceGroupName $ResourceGroup.ResourceGroupName
if (-not $DataFactory) {
$DataFactory = Set-AzDataFactoryV2 -ResourceGroupName $ResourceGroup.ResourceGroupName -Location $ResourceGroup.Location -Name $DataFactoryName
if ($DataFactory) {
"Data Factory {0} Created Successfully" -f $DataFactory.DataFactoryName
}
else {
"ERROR: Data Factory Creation UNSUCCESSFUL"
}
}
else {
"Data Factory {0} Already Exists" -f $DataFactory.DataFactoryName
}
# Creating Azure SQL Server and Database
$ServerName = "xxxxx"
$DatabaseName = "xxxxx"
$AzSQLServer = Get-AzSqlServer -ServerName $ServerName
$Subscription = Get-AzSubscription
"Subscription Data" -f $Subscription.Id
if (-not $AzSQLServer) {
"Creating New Azure SQL Server"
$AdminSqlLogin = "xxxxx"
$Password = "xxxxx"
$StartIp = "xxxxx.xxxxx.xxxxx.xxxxx"
$EndIp = "xxxxx.xxxxx.xxxxx.xxxxx"
$AzSQLServer = New-AzSqlServer -ResourceGroupName $ResourceGroupName `
-ServerName $ServerName `
-Location $Location `
-SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminSqlLogin, $(ConvertTo-SecureString -String $Password -AsPlainText -Force))
if ($AzSQLServer) {
$FireWallRule = New-AzSqlServerFirewallRule -ResourceGroupName $ResourceGroupName `
-ServerName $ServerName `
-FirewallRuleName "AllowedIPs" -StartIpAddress $StartIp -EndIpAddress $EndIp
if ($FireWallRule) {
"Server Created Successfully {0} with firewall Rule Setup" -f $AzSQLServer.ServerName
}
else {
"Server Created Successfully {0} No FireWall Setup" -f $AzSQLServer.ServerName
}
}
else {
"ERROR: Server Creation UNSUCCESSFUL"
}
}
else {
"Server Exists {0}" -f $AzSQLServer.ServerName
}
$AzSQLDatabase = Get-AzSqlDatabase -DatabaseName $DatabaseName -ServerName $ServerName -ResourceGroupName $ResourceGroup.ResourceGroupName
if (-not $AzSQLDatabase) {
"Creating New Azure SQL Database"
$Parameters = #{
ResourceGroupName = $ResourceGroupName
ServerName = $ServerName
DatabaseName = $DatabaseName
RequestedServiceObjectiveName = 'S0'
}
$AzSQLDatabase = New-AzSqlDatabase #Parameters
if ($AzSQLDatabase) {
"Azure SQL Database {0} Created Successfully " -f $AzSQLDatabase.DatabaseName
}
else {
"ERROR: Azure SQL Database Creation UNSUCCESSFUL"
}
}
else {
"Database {0} Exists " -f $AzSQLDatabase.DatabaseName
}
You could use Clear-AzContext to remove all Azure credentials, account, and subscription information. Then use Connect-AzAccount -Tenant xxxxx -Subscription xxxxx, it should work.

Export SQL Azure db to blob - Start-AzureSqlDatabaseExport : Cannot convert AzureStorageContainer to AzureStorageContainer

I am using this code found on stack , and all connections are correct.
Import-Module Azure
Import-Module Azure.Storage
Get-AzureRmSubscription –SubscriptionName “Production” | Select-AzureRmSubscription
# Username for Azure SQL Database server
$ServerLogin = "username"
# Password for Azure SQL Database server
$serverPassword = ConvertTo-SecureString "abcd" -AsPlainText -Force
# Establish credentials for Azure SQL Database Server
$ServerCredential = new-object System.Management.Automation.PSCredential($ServerLogin, $serverPassword)
# Create connection context for Azure SQL Database server
$SqlContext = New-AzureSqlDatabaseServerContext -FullyQualifiedServerName “myspecialsqlserver.database.windows.net” -Credential $ServerCredential
$StorageContext = New-AzureStorageContext -StorageAccountName 'prodwad' -StorageAccountKey 'xxxxx'
$Container = Get-AzureStorageContainer -Name 'automateddbbackups' -Context $StorageContext
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlContext -StorageContainer $Container -DatabaseName 'Users' -BlobName 'autobackupotest.bacpac' -Verbose -Debug
I am getting this error. I have spent hours on this.
Start-AzureSqlDatabaseExport : Cannot bind parameter 'StorageContainer'. Cannot convert the
"Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageContainer" value of type
"Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageContainer" to type
"Microsoft.WindowsAzure.Commands.Common.Storage.ResourceModel.AzureStorageContainer".
At line:31 char:99
+ ... SqlConnectionContext $SqlContext -StorageContainer $Container -Databa ...
+ ~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-AzureSqlDatabaseExport], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet.StartAzureSqlDatabaseExport
I am using AzureRM 3.8.0
According to your description and codes, If you want to start a new sqldatabase export.I suggest you could try below codes. It will work well.
$subscriptionId = "YOUR AZURE SUBSCRIPTION ID"
Login-AzureRmAccount
Set-AzureRmContext -SubscriptionId $subscriptionId
# Database to export
$DatabaseName = "DATABASE-NAME"
$ResourceGroupName = "RESOURCE-GROUP-NAME"
$ServerName = "SERVER-NAME"
$serverAdmin = "ADMIN-NAME"
$serverPassword = "ADMIN-PASSWORD"
$securePassword = ConvertTo-SecureString -String $serverPassword -AsPlainText -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $serverAdmin, $securePassword
# Generate a unique filename for the BACPAC
$bacpacFilename = $DatabaseName + (Get-Date).ToString("yyyyMMddHHmm") + ".bacpac"
# Storage account info for the BACPAC
$BaseStorageUri = "https://STORAGE-NAME.blob.core.windows.net/BLOB-CONTAINER-NAME/"
$BacpacUri = $BaseStorageUri + $bacpacFilename
$StorageKeytype = "StorageAccessKey"
$StorageKey = "YOUR STORAGE KEY"
$exportRequest = New-AzureRmSqlDatabaseExport -ResourceGroupName $ResourceGroupName -ServerName $ServerName `
-DatabaseName $DatabaseName -StorageKeytype $StorageKeytype -StorageKey $StorageKey -StorageUri $BacpacUri `
-AdministratorLogin $creds.UserName -AdministratorLoginPassword $creds.Password
$exportRequest
# Check status of the export
Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $exportRequest.OperationStatusLink
Then you could use Get-AzureRmSqlDatabaseImportExportStatus to see the details information, like below:
I got the same problem after updating some powershell packages which I do not remember exactly. After the update my scripts started to fail.
My solution is :
Install the latest AzureRM from nuget via powershell
Use the other overload of Start-AzureSqlDatabaseExport which utilizes the parameters
-StorageContainerName and -StorageContext rather than -StorageContainer
It looks like if you pass the parameters to the function it will create the container object internally without crashing.

Cannot find type Microsoft.WindowsAzure.Commands.SqlDatabase.Services.ImportExportRequest

I am backing up Azure SQL Database with PowerShell. The final part of the script, which is working fine, is this:
Write-Output "Exporting databases"
foreach ($db in $azSqlServerDatabases) {
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $azSqlStageConnContext -StorageContainer $container -DatabaseName $db.Name -BlobName ($db.Name + ".bacpac")
$exportRequests.Add($exportRequest)
Write-Output ($db.Name + ".bacpac")
}
I am trying to create generic list:
$exportRequests = New-Object 'System.Collections.Generic.List[Microsoft.WindowsAzure.Commands.SqlDatabase.Services.ImportExportRequest]'
Which must hold the results of the requests. The problem is that when I create the generic list I get an error:
New-Object : Cannot find type [System.Collections.Generic.List[Microsoft.WindowsAzure.Commands.SqlDatabase.Services.ImportExportRequest]]: verify that the assembly containing this type is lo
aded.
At C:...
+ ... tRequests = New-Object 'System.Collections.Generic.List[Microsoft.Win ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
Where can I find this type? Why it is not included - I am calling Start-AzureSqlDatabaseExport successfully and I get the result object - so the type is known already.
Trying to create just one object of the type manually in the Azure PowerShell Console throws the same exception:
PS C:\> $x = new-object 'Microsoft.WindowsAzure.Commands.SqlDatabase.Services.ImportExportRequest'
new-object : Cannot find type [Microsoft.WindowsAzure.Commands.SqlDatabase.Services.ImportExportRequest]: verify that t
he assembly containing this type is loaded.
At line:1 char:6
+ $x = new-object 'Microsoft.WindowsAzure.Commands.SqlDatabase.Services ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
PS C:\>
I got the output type from MS documentation.
I ran getType() on the object returned by Start-AzureSQLDatabaseExport. Looks like you ran into a type issue. The actual type of the object returned by Start-AzureSQLDatabaseExport is Microsoft.WindowsAzure.Commands.SqlDatabase.Model.SqlDatabaseServerOperationContext.
Try declaring your list like below:
$exportRequests = New-Object 'System.Collections.Generic.List[Microsoft.WindowsAzure.Commands.SqlDatabase.Model.SqlDatabaseServerOperationContext]'
Thank you #elfisher for the assistance. Here is the final version of my command just in case somebody find it helpful. It helps me export all the dbs from azure server during dev and test.
# The command will prompt only once for most parameters during one session
param(
[string] $azSubscriptionId,
[string] $azStorageName,
[string] $azStorageKey,
[string] $azContainerName,
[string] $azSqlServerName,
[string] $azSqlServerUserName,
[string] $azSqlServerPassword)
#if you want to clean up all globally created vars => Remove-Variable -Name 'az*'
Remove-Variable -Name 'az*'
#Remove-Variable -Name 'azAccount' # clean up acc credentials. Can be removed but once in a while the credentials for the account get expired
#region azAccount
$azAccount = Get-AzureAccount
if(!$azAccount)
{
Do
{
Write-Output "No azure account. Prompting ..."
$azAccount = Add-AzureAccount
} While (!$azAccount)
Set-Variable -Name azAccount -Value $azAccount -Scope Global
$azAccount = Get-AzureAccount
}
#endregion
#region azSubscriptionId
if(!$azSubscriptionId)
{
Do
{
Write-Output "No subscription Id. Prompting ..."
$azSubscriptionId = Read-Host "Subscription Id"
} While (!$azSubscriptionId)
Write-Output "Input for subscription Id $azSubscriptionId"
Set-Variable -Name azSubscriptionId -Value $azSubscriptionId -Scope Global
}
Select-AzureSubscription -SubscriptionId $azSubscriptionId
Write-Output "Selected subscription Id $azSubscriptionId"
#endregion
#region azStorageName
if(!$azStorageName)
{
Do
{
Write-Output "No storage name. Prompting ..."
$azStorageName = Read-Host "storage name"
} While (!$azStorageName)
Set-Variable -Name storageName -Value $azStorageName -Scope Global
}
#endregion
#region azStorageKey
if(!$azStorageKey)
{
Do
{
Write-Output "No storage key. Prompting ..."
$azStorageKey = Read-Host "storage key"
} While (!$azStorageKey)
Set-Variable -Name azStorageKey -Value $azStorageKey -Scope Global
}
#endregion
#region azContainerName
if(!$azContainerName)
{
Do
{
Write-Output "No container name. Prompting ..."
$azContainerName = Read-Host "container name"
} While (!$azContainerName)
Set-Variable -Name azContainerName -Value $azContainerName -Scope Global
}
#endregion
#region azSqlServerName
if(!$azSqlServerName)
{
Do
{
Write-Output "No sql server name. Prompting ..."
$azSqlServerName = Read-Host "sql server name"
} While (!$azSqlServerName)
Set-Variable -Name azSqlServerName -Value $azSqlServerName -Scope Global
}
#endregion
#region azSqlServer
if(!$azSqlServer)
{
Write-Output "No sql server variable stored on this PC. Prompting ..."
$azSqlServer = Get-AzureSqlDatabaseServer -ServerName $azSqlServerName
Set-Variable -Name azSqlServer -Value $azSqlServer -Scope Global
}
#endregion
#region azSqlServerCredenials
if(!$azSqlServerCredenials)
{
Do
{
Write-Output "No sql server credentials. Prompting ..."
$azSqlServerCredenials = Get-Credential "Enter Credentials for $azSqlServerName"
} While (!$azSqlServerCredenials)
Set-Variable -Name azSqlServerCredenials -Value $azSqlServerCredenials -Scope Global
}
#endregion
#region Sql connection context
if(!$azSqlCtx)
{
Write-Output "No Sql Server Context. Creating..."
$azSqlCtx = New-AzureSqlDatabaseServerContext -ServerName $azSqlServer.ServerName -Credential $azSqlServerCredenials
Set-Variable -Name azSqlCtx -Value $azSqlCtx -Scope Global
Write-Output "Sql Server Context for $azSqlServer.ServerName created."
}
#endregion
#region Storage connection context
if(!$azStorageCtx)
{
Write-Output "No Storage Context. Creating..."
$azStorageCtx = New-AzureStorageContext -StorageAccountName $azStorageName -StorageAccountKey $azStorageKey
Set-Variable -Name azStorageCtx -Value $azStorageCtx -Scope Global
Write-Output "Storage context for $azStorageName created."
}
#endregion
#region Storage container ref
if(!$azStorageContainer)
{
Write-Output "No container ref. Creating for $azContainerName"
$azStorageContainer = Get-AzureStorageContainer -Name $azContainerName -Context $azStorageCtx
Set-Variable -Name azStorageContainer -Value $azStorageContainer -Scope Global
Write-Output "Container ref to $azStorageContainer created."
}
#endregion
#region Sql Databases ref
if(!$azSqlServerDatabases)
{
Write-Output "No Sql Databases array ref. Creating..."
$azSqlServerDatabases = Get-AzureSqlDatabase -ConnectionContext $azSqlCtx
Set-Variable -Name azSqlServerDatabases -Value $azSqlServerDatabases -Scope Global
Write-Output "Sql Databases array ref created."
}
#endregion
#region actual export of azure databases
$exportRequests = New-Object 'System.Collections.Generic.List[Microsoft.WindowsAzure.Commands.SqlDatabase.Model.SqlDatabaseServerOperationContext]'
Write-Output "Exporting databases"
foreach ($db in $azSqlServerDatabases) {
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $azSqlCtx -StorageContainer $azStorageContainer -DatabaseName $db.Name -BlobName ($db.Name + ".bacpac")
$exportRequests.Add($exportRequest)
Write-Output ($db.Name + ".bacpac")
}
#endregion
#import dbs back into your local server
#cd [FOLDERPATH]
#$goodlist = dir
# probably the correct path
##C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\SQLDB\DAC\120
#cd 'C:\Program Files (x86)\Microsoft SQL Server\110\DAC\bin'
#foreach($i in $goodlist){ $name = $i.Name; $namer = $i.Name.Substring(0, $i.Name.length - 7); .\SqlPackage.exe /a:Import /sf:[FOLDERPATH]\$name /tdn:$namer /tsn:[SERVERNAME] }

Resources