Azure SQL托管实例SQL Agent作业PowerShell Az模块安装及运行问题
Azure托管实例SQL Agent中运行PowerShell恢复脚本的问题解决
问题描述
通过SSMS配置SQL Agent作业,每日调度执行PowerShell脚本实现Azure托管实例数据库的时间点恢复时,出现两个错误:
The term 'Get-AzSubscription' is not recognized as the name of a cmdlet, function, script file, or operable program. Process Exit Code -1. The step failed
尝试执行Install-Module -Name Az -Force -AllowClobber -Scope AllUsers时,又提示Install-Module not recognized。脚本在Azure门户的PowerShell环境可正常运行,但SQL Agent作业中无法执行,同时已知托管实例SQL Agent不支持PowerShell Core。
原脚本内容:
$subscriptionId = "xxxxxxxxxxxxxxxxxxxxxxxxxx" $resourceGroupName = "xxxxxx" $managedInstanceName = "az-xxxxxxx" $databaseName = "prod" $pointInTime = "2025-02-16T11:30:39.3882806Z" $targetDatabase = "supp" Get-AzSubscription -SubscriptionId $subscriptionId Select-AzSubscription -SubscriptionId $subscriptionId Restore-AzSqlInstanceDatabase -FromPointInTimeBackup -ResourceGroupName $resourceGroupName -InstanceName $managedInstanceName -Name $databaseName -PointInTime $pointInTime -TargetInstanceDatabaseName $targetDatabase
核心原因
Azure托管实例的SQL Agent运行在受限的沙箱环境中:
- 默认使用Windows PowerShell 5.1,但未预装Az模块
- 沙箱限制了管理员权限,无法直接执行
Install-Module命令安装模块
解决方案
方案1:使用Azure自动化账户(推荐)
利用Azure自动化账户托管恢复逻辑,再通过SQL Agent触发执行:
- 在Azure门户创建自动化账户,系统会默认预装常用Az模块,也可手动添加缺失模块
- 将恢复脚本导入为自动化账户的运行手册,配置具备托管实例恢复权限的运行账户
- 在SQL Agent作业中创建CmdExec步骤,通过Azure CLI或REST API触发运行手册执行
方案2:改用Azure CLI替代PowerShell Cmdlet
托管实例SQL Agent环境通常预装Azure CLI,可将原PowerShell逻辑转换为Azure CLI命令:
az account set --subscription xxxxxxxxxxxxxxxxxxxxxxxxxx az sql midb restore --resource-group xxxxxx --managed-instance az-xxxxxxx --name prod --restore-point "2025-02-16T11:30:39.3882806Z" --target-database supp
在SQL Agent作业中创建CmdExec步骤,执行上述命令即可。
关键注意事项
- 托管实例SQL Agent仅支持Windows PowerShell 5.1,且无法自行安装Az模块
- 无论采用哪种方案,执行身份需具备托管实例的
Contributor或SQL Managed Instance Contributor角色,以及数据库恢复权限
内容的提问来源于stack exchange,提问作者Djamel
相关产品推荐
相关产品推荐

