DevOps自托管Agent执行Get-AzStorageAccount cmdlet报错求助
在连接到myMachine的自托管Azure DevOps Agent上,通过流水线的PowerShell任务执行以下脚本时出错:
$context = (Get-AzStorageAccount -ResourceGroupName "myResource" -Name "myResourceStorage").Context
错误信息:
The term 'Get-AzStorageAccount' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again
手动在myMachine上执行脚本完全正常,但添加Import-Module -Name Az或Import-Module -Name Az.Accounts后,流水线执行时出现新错误:
The specified module 'Az.Accounts' was not loaded because no valid module file was found in any module directory
Az模块安装路径为C:\Users\myAdminUser\Documents\WindowsPowerShell\Modules。
检查自托管Agent的运行账户
自托管Agent默认使用NT AUTHORITY\SYSTEM系统账户运行,而Az模块安装在myAdminUser的个人模块目录下,系统账户无法访问该路径。- 操作:打开Windows服务,找到Azure DevOps Agent服务,查看其登录账户;在流水线中执行
$env:USERNAME和$env:PSModulePath,对比手动执行的结果。 - 修复:将Agent服务的登录账户改为
myAdminUser,或者把Az模块安装到公共模块路径(C:\Program Files\WindowsPowerShell\Modules)。
- 操作:打开Windows服务,找到Azure DevOps Agent服务,查看其登录账户;在流水线中执行
显式指定模块路径导入
如果不想变更Agent账户或模块路径,可在脚本开头显式指定模块所在路径导入:$azModulePath = "C:\Users\myAdminUser\Documents\WindowsPowerShell\Modules" Import-Module (Join-Path $azModulePath "Az.Accounts") -Force Import-Module (Join-Path $azModulePath "Az.Storage") -Force同时要确保Agent运行账户对该路径有读取权限,必要时给
C:\Users\myAdminUser\Documents文件夹添加系统账户的读取权限。改用Azure PowerShell任务
Azure DevOps提供的Azure PowerShell任务专门适配Azure模块操作,会自动处理模块的环境配置,无需手动导入。配置任务时选择对应Az模块版本即可自动加载所需模块。手动添加模块路径到PSModulePath
在流水线脚本开头,先将Az模块所在路径添加到PowerShell的模块搜索路径中:$env:PSModulePath += ";C:\Users\myAdminUser\Documents\WindowsPowerShell\Modules" Import-Module Az -Force重新安装Az模块到公共路径
以管理员身份打开PowerShell,执行以下命令将Az模块安装到所有用户可访问的公共路径:Install-Module -Name Az -Scope AllUsers -Force
内容的提问来源于stack exchange,提问作者Tim Geoman

