运行 使用 az 模板在 Azure 函数上执行 Powershell 命令

Run Powershell commands on Azure Function with az template

我想编写一个脚本,将 Azure SQL 数据库拉入 Azure SQL 弹性池。但这应该是来自 Azure Function

的 运行

但是得到这个错误: 错误:指定的模块 'AzureRM.Compute' 未加载,因为在任何模块目录中均未找到有效的模块文件。

当我包含 Azure RM 时,我收到一个新错误,因为我无法使用 AzureRM 和 Az 命令。

我可以只使用 AZ 命令连接到我想要的订阅吗?

以下是我正在尝试的代码:

$resourceGroupName = "<VALUE>"
$location = "<VALUE>"
$PoolName = "<VALUE>"
$adminSqlLogin = "<VALUE>"
$password = "<VALUE>"
$serverName = "<VALUE>.database.windows.net,1433"
$DatabaseName = "<VALUE>"

Set-ExecutionPolicy Unrestricted -Scope CurrentUser


Import-Module Az.Sql

$azureAccountName ="<VALUE>"
$azurePassword = "<VALUE>" | ConvertTo-SecureString -AsPlainText -Force

$psCred = New-Object System.Management.Automation.PSCredential($azureAccountName, $azurePassword)

Login-AzureRmAccount -Credential $psCred -SubscriptionId $subscriptionId

Set-AzSqlDatabase -ResourceGroupName $resourceGroupName `
    -ServerName $serverName `
    -DatabaseName $DatabaseName `
    -ElasticPoolName $PoolName

但在 Azure 函数中出现以下错误:

Login-AzureRmAccount : Method 'get_SerializationSettings' in type 'Microsoft.Azure.Management.Internal.Resources.ResourceManagementClient' from assembly 'Microsoft.Azure.Commands.ResourceManager.Common, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not have an implementation.

不应混合使用 AZ 和 ARM cmdlet。我建议您只使用新的 AZ cmdlet。如果您在 Azure 函数中使用托管标识,您甚至不必手动连接到您的 Azure 帐户,因为这已经在配置文件中为您完成了。ps1:

if ($env:MSI_SECRET -and (Get-Module -ListAvailable Az.Accounts)) {
    Connect-AzAccount -Identity
}

只需确保将 Az 添加到 requirements.psd1:

@{
    Az = '1.*'
}