Azure Durable函数中Az.Compute模块重复加载报错问题咨询
问题
我在Azure Functions中设计了一个Durable函数应用,依次触发两个任务:
# the orchestrator function param($context) $tasks += Invoke-DurableActivity -FunctionName "Func1-GetAzVm" -Input "testinput" -NoWait $tasks += Invoke-DurableActivity -FunctionName "Func2-Invoke-AzVMRunCommand" -Input "testinput" -NoWait $output = Wait-DurableTask -Task $tasks
其中Func2-Invoke-AzVMRunCommand的代码如下:
# stuff above # 取消注释以下代码后,函数会尝试再次隐式导入Az.Compute,进而触发下方错误 #$result = Invoke-AzVMRunCommand ` # -ResourceGroupName $inputParams.ResourcegroupName ` # -VMName $inputParams.Name ` # -CommandId "RunShellScript" ` # -ScriptString $linuxScript # stuff below
本地仅运行Func1时一切正常,但添加Func2的执行代码后,出现如下错误:
[2025-05-17T01:21:06.764Z] InvocationName : Invoke-AzVMRunCommand [2025-05-17T01:21:06.764Z] CommandOrigin : Internal [2025-05-17T01:21:06.764Z] ScriptStackTrace : at <ScriptBlock>, /<FILE_PATH>/Func2--Invoke-AzVMRunCommand/run.ps1: line 12 [2025-05-17T01:21:06.764Z] [2025-05-17T01:21:06.764Z] [2025-05-17T01:21:06.764Z] Exception: The 'Invoke-AzVMRunCommand' command was found in the module 'Az.Compute', but the module could not be loaded due to the following error: [Assembly with same name is already loaded] [2025-05-17T01:21:06.764Z] For more information, run 'Import-Module Az.Compute'.
请问为何Az.Compute模块会被隐式加载两次?目前我甚至考虑改用Python重写来规避该问题。
分析与解决方法
模块重复加载的原因
- Azure Functions进程复用机制:Azure Functions为提升性能会复用函数宿主进程,Func1执行时已隐式加载Az.Compute模块,后续Func2在同一进程启动时,尝试再次隐式导入该模块,就会触发"同名程序集已加载"的冲突。
- 隐式导入时机差异:Func1调用的
Get-AzVm属于Az.Compute模块,执行时自动导入该模块;Func2启用Invoke-AzVMRunCommand后,PowerShell会再次尝试查找并导入Az.Compute,此时进程中已有该模块的程序集,冲突由此产生。
具体解决步骤
- 显式统一导入模块:在两个活动函数的开头,添加指定版本的模块导入命令,避免隐式导入的版本或加载时机差异:
可通过Import-Module Az.Compute -RequiredVersion <你的模块版本号> -ForceGet-Module Az.Compute查看当前使用的版本号。 - 调试时禁用进程复用:本地开发阶段,可在
local.settings.json中添加"FUNCTIONS_WORKER_PROCESS_COUNT": 1和"WEBSITE_DISABLE_WORKER_REUSE": true,强制每个函数运行在独立进程中验证问题,但生产环境不建议使用,会影响性能。 - 检查模块依赖版本:确认Func1和Func2是否依赖不同版本的Az模块,确保整个函数应用使用统一版本的Az模块,避免版本不一致引发的加载冲突。
无需改用Python,通过上述方法即可解决该问题。
内容的提问来源于stack exchange,提问作者Ryu S.
相关产品推荐
相关产品推荐

