使用 PowerShell 將 BACPAC 檔案匯入 Azure SQL 資料庫Use PowerShell to import a BACPAC file into an Azure SQL database

此 PowerShell 指令碼範例會從 BACPAC 檔案將資料庫匯入 Azure SQL 資料庫。This PowerShell script example imports a database from a BACPAC file into an Azure SQL database.

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

注意

本文已更新為使用新的 Azure PowerShell Az 模組。This article has been updated to use the new Azure PowerShell Az module. AzureRM 模組在至少 2020 年 12 月之前都還會持續收到錯誤 (Bug) 修正,因此您仍然可以持續使用。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要深入了解新的 Az 模組和 AzureRM 的相容性,請參閱新的 Azure PowerShell Az 模組簡介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 如需 Az 模組安裝指示,請參閱安裝 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell 可讓您使用 bashPowerShell 以與 Azure 服務搭配使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要啟動 Azure Cloud Shell:To launch Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Launch Cloud Shell.

  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.

  3. 在 Windows 和 Linux 上按 Ctrl+Shift+V;或在 macOS 上按 Cmd+Shift+V,將程式碼貼到 Cloud Shell工作階段中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.

  4. 按下 Enter 鍵執行程式碼。Press Enter to run the code.

如果選擇在本機安裝和使用 PowerShell,此教學課程需要 AZ PowerShell 1.4.0 或更新版本。If you choose to install and use the PowerShell locally, this tutorial requires AZ PowerShell 1.4.0 or later. 如果您需要升級,請參閱安裝 Azure PowerShell 模組If you need to upgrade, see Install Azure PowerShell module. 如果您在本機執行 PowerShell,則也需要執行 Connect-AzAccount 以建立與 Azure 的連線。If you are running PowerShell locally, you also need to run Connect-AzAccount to create a connection with Azure.

範例指令碼Sample script

# Connect-AzAccount
# The SubscriptionId in which to create these objects
$SubscriptionId = ''
# Set the resource group name and location for your server
$resourceGroupName = "myResourceGroup-$(Get-Random)"
$location = "westeurope"
# Set an admin login and password for your server
$adminSqlLogin = "SqlAdmin"
$password = "ChangeYourAdminPassword1"
# Set server name - the logical server name has to be unique in the system
$serverName = "server-$(Get-Random)"
# The sample database name
$databaseName = "myImportedDatabase"
# The storage account name and storage container name
$storageAccountName = "sqlimport$(Get-Random)"
$storageContainerName = "importcontainer$(Get-Random)"
# BACPAC file name
$bacpacFilename = "sample.bacpac"
# The ip address range that you want to allow to access your server
$startip = "0.0.0.0"
$endip = "0.0.0.0"

# Set subscription 
Set-AzContext -SubscriptionId $subscriptionId 

# Create a resource group
$resourcegroup = New-AzResourceGroup -Name $resourceGroupName -Location $location

# Create a storage account 
$storageAccount = New-AzStorageAccount -ResourceGroupName $resourceGroupName `
    -AccountName $storageAccountName `
    -Location $location `
    -Type "Standard_LRS"

# Create a storage container 
$storageContainer = New-AzStorageContainer -Name $storageContainerName `
    -Context $(New-AzStorageContext -StorageAccountName $storageAccountName `
        -StorageAccountKey $(Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName).Value[0])

# Download sample database from Github
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 #required by Github
Invoke-WebRequest -Uri "https://github.com/Microsoft/sql-server-samples/releases/download/wide-world-importers-v1.0/WideWorldImporters-Standard.bacpac" -OutFile $bacpacfilename

# Upload sample database into storage container
Set-AzStorageBlobContent -Container $storagecontainername `
    -File $bacpacFilename `
    -Context $(New-AzStorageContext -StorageAccountName $storageAccountName `
        -StorageAccountKey $(Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName).Value[0])

# Create a new server with a system wide unique server name
$server = New-AzSqlServer -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -Location $location `
    -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminSqlLogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force))

# Create a server firewall rule that allows access from the specified IP range
$serverFirewallRule = New-AzSqlServerFirewallRule -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -FirewallRuleName "AllowedIPs" -StartIpAddress $startIp -EndIpAddress $endIp

# Import bacpac to database with an S3 performance level
$importRequest = New-AzSqlDatabaseImport -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -DatabaseName $databaseName `
    -DatabaseMaxSizeBytes "262144000" `
    -StorageKeyType "StorageAccessKey" `
    -StorageKey $(Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -StorageAccountName $storageAccountName).Value[0] `
    -StorageUri "https://$storageaccountname.blob.core.windows.net/$storageContainerName/$bacpacFilename" `
    -Edition "Standard" `
    -ServiceObjectiveName "S3" `
    -AdministratorLogin "$adminSqlLogin" `
    -AdministratorLoginPassword $(ConvertTo-SecureString -String $password -AsPlainText -Force)

# Check import status and wait for the import to complete
$importStatus = Get-AzSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink
[Console]::Write("Importing")
while ($importStatus.Status -eq "InProgress")
{
    $importStatus = Get-AzSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink
    [Console]::Write(".")
    Start-Sleep -s 10
}
[Console]::WriteLine("")
$importStatus

# Scale down to S0 after import is complete
Set-AzSqlDatabase -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -DatabaseName $databaseName  `
    -Edition "Standard" `
    -RequestedServiceObjectiveName "S0"

# Clean up deployment 
# Remove-AzResourceGroup -ResourceGroupName $resourceGroupName

清除部署Clean up deployment

使用下列命令來移除資源群組及其所有相關聯的資源。Use the following command to remove the resource group and all resources associated with it.

Remove-AzResourceGroup -ResourceGroupName $resourcegroupname

指令碼說明Script explanation

此指令碼會使用下列命令。This script uses the following commands. 下表中的每個命令都會連結至命令特定的文件。Each command in the table links to command specific documentation.

命令Command 注意Notes
New-AzResourceGroupNew-AzResourceGroup 建立用來存放所有資源的資源群組。Creates a resource group in which all resources are stored.
New-AzSqlServerNew-AzSqlServer 建立裝載單一資料庫和彈性集區的 SQL Database 伺服器。Creates a SQL Database server that hosts single databases and elastic pools.
New-AzSqlServerFirewallRuleNew-AzSqlServerFirewallRule 建立 SQL Database 伺服器防火牆規則,以允許從輸入的 IP 位址範圍,存取 SQL Database 伺服器上的所有單一資料庫和集區資料庫。Creates a SQL Database server firewall rule to allow access to all single databases and pooled database on the SQL Database server from the entered IP address range.
New-AzSqlDatabaseImportNew-AzSqlDatabaseImport 在伺服器上匯入 BACPAC 檔案並建立新的資料庫。Imports a BACPAC file and create a new database on the server.
Remove-AzResourceGroupRemove-AzResourceGroup 刪除資源群組,包括所有的巢狀資源。Deletes a resource group including all nested resources.

後續步驟Next steps

如需有關 Azure PowerShell 的詳細資訊,請參閱 Azure PowerShell 文件For more information on the Azure PowerShell, see Azure PowerShell documentation.

其他的 SQL Database PowerShell 指令碼範例可於 Azure SQL Database PowerShell 指令碼中找到。Additional SQL Database PowerShell script samples can be found in the Azure SQL Database PowerShell scripts.