Azure PowerShell重连后如何恢复APIM资源变量值?
解决APIM创建后终端超时导致变量为空的问题
方法1:重新获取APIM资源实例
终端重连后直接通过资源组和服务名称重新拉取APIM对象,替代丢失的$apimService变量,后续配置命令可正常执行:
# 重新获取APIM实例 $apimService = Get-AzApiManagement -ResourceGroupName $resGroupName -Name $apimServiceName # 继续执行自定义主机名配置 $proxyHostnameConfig = New-AzApiManagementCustomHostnameConfiguration ` -Hostname $gatewayHostname ` -HostnameType Proxy ` -PfxPath $gatewayCertPfxPath ` -PfxPassword $certPwd $apimService.ProxyCustomHostnameConfiguration = $proxyHostnameConfig # 执行保存命令使配置生效 Set-AzApiManagement -InputObject $apimService
方法2:调整PowerShell超时设置
修改会话超时参数,避免长时间运行的命令被中断:
# 延长Azure PowerShell操作超时时间(设置为7200秒即2小时) $AzContext = Get-AzContext $AzContext.Environment.ResourceManagerEndpoint += "?api-version=2021-04-01&timeout=7200" Set-AzContext -Context $AzContext
也可直接在创建命令中指定超时参数:
$apimService = New-AzApiManagement ` -ResourceGroupName $resGroupName ` -Location $location ` -Name $apimServiceName ` -Organization $apimOrganization ` -AdminEmail $apimAdminEmail ` -VirtualNetwork $apimVirtualNetwork ` -VpnType "Internal" ` -Sku "Developer" ` -TimeoutSec 7200
方法3:使用后台作业执行APIM创建
将APIM创建命令放到后台作业中运行,即使终端断开,作业仍会在后台执行,后续可重新连接后获取结果:
# 启动后台作业创建APIM Start-Job -Name CreateAPIM -ScriptBlock { param($resGroupName, $location, $apimServiceName, $apimOrganization, $apimAdminEmail, $apimVirtualNetwork) New-AzApiManagement ` -ResourceGroupName $resGroupName ` -Location $location ` -Name $apimServiceName ` -Organization $apimOrganization ` -AdminEmail $apimAdminEmail ` -VirtualNetwork $apimVirtualNetwork ` -VpnType "Internal" ` -Sku "Developer" } -ArgumentList $resGroupName, $location, $apimServiceName, $apimOrganization, $apimAdminEmail, $apimVirtualNetwork # 后续查看作业状态并获取结果 $job = Get-Job -Name CreateAPIM Wait-Job $job $apimService = Receive-Job $job
方法4:拆分脚本分阶段执行
将操作拆分为两个独立脚本:
- 第一脚本仅负责创建APIM,执行完成后通过Azure门户或
Get-AzApiManagement确认资源状态为Online。 - 第二脚本单独执行自定义主机名配置,开头先通过
Get-AzApiManagement获取实例,再进行后续配置。
内容的提问来源于stack exchange,提问作者Jananath Banuka
相关产品推荐
相关产品推荐

