You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure DevOps中Az.KeyVault模块加载异常:命令存在却无法加载

解决Azure DevOps流水线中Az.KeyVault模块加载冲突问题

我在借助Let's Encrypt证书与Azure Key Vault实现自动续期流程时(基于posh-acme-azure-example仓库),遇到了Az.KeyVault模块加载异常的问题:先是执行脚本时提示Get-AzKeyVaultCertificate命令存在但模块无法加载,手动添加Import-Module Az.KeyVault -Force后又出现Assembly with the same name is already loaded错误。

问题根源

Azure DevOps的托管代理默认预装了Az模块套件,手动安装的模块版本与预装版本冲突,导致PowerShell无法正确加载模块(同一程序集的不同版本不能同时加载)。

解决方案

方案1:使用AzurePowerShell任务替代手动安装模块

AzurePowerShell任务会自动管理Az模块的版本和加载,避免冲突。将原PowerShell@2任务替换为以下配置:

- task: AzurePowerShell@5
  displayName: 运行证书续期脚本
  inputs:
    azureSubscription: '<你的Azure服务连接名称>'
    ScriptType: 'FilePath'
    ScriptPath: '<你的续期脚本路径>'
    azurePowerShellVersion: 'LatestVersion' # 或指定具体版本,比如 '9.6.0'
    pwsh: true

方案2:调整手动安装/导入逻辑,避免版本冲突

如果必须使用PowerShell@2任务,可按以下步骤修改:

  1. 清理现有冲突模块(可选,若预装版本不兼容):

    # 卸载所有已加载的Az模块
    Get-Module Az* | Remove-Module -Force
    # 卸载已安装的Az模块版本
    Uninstall-Module Az* -AllVersions -Force -ErrorAction SilentlyContinue
    
  2. 指定版本安装模块:
    选择与Posh-ACME兼容的Az模块版本,统一安装相同版本:

    - task: PowerShell@2
      displayName: 安装并导入指定版本模块
      inputs:
        targetType: 'inline'
        script: |
          Install-Module Az.Accounts, Az.KeyVault, Az.Resources, Posh-ACME `
            -RequiredVersion 9.6.0 `
            -Force `
            -SkipPublisherCheck `
            -AllowClobber
    
          # 按版本导入模块
          Import-Module Az.Accounts -RequiredVersion 9.6.0 -Force
          Import-Module Az.KeyVault -RequiredVersion 9.6.0 -Force
          Import-Module Az.Resources -RequiredVersion 9.6.0 -Force
          Import-Module Posh-ACME -Force
        errorActionPreference: 'stop'
        failOnStderr: true
        pwsh: true
    
  3. 跳过版本检查导入模块:
    若不需要更换版本,仅需解决加载问题,可使用-SkipEditionCheck参数导入:

    Import-Module Az.KeyVault -Force -SkipEditionCheck
    

验证方法

在流水线中添加步骤,检查模块加载状态:

Get-Module Az.KeyVault
Get-Command Get-AzKeyVaultCertificate

内容的提问来源于stack exchange,提问作者RNK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 03:20:24