如何解决Azure Function App中PowerShell模块的TLS认证错误?
问题根源与解决方案
问题根源
你遇到的核心问题是Windows PowerShell兼容会话(WinPSCompatSession)的环境隔离:
- 当使用
-UseWindowsPowerShell加载模块时,模块并非运行在当前的PowerShell Core会话中,而是运行在一个独立的Windows PowerShell 5.1兼容会话里。 - 你在主会话中设置的
[Net.ServicePointManager]::SecurityProtocol = Tls12只会作用于PowerShell Core环境,不会同步到这个隔离的兼容会话。 - Windows PowerShell 5.1默认的安全协议可能包含已被Azure AD弃用的TLS 1.0/1.1,导致模块认证时触发AADSTS1002016错误。
- 你在Function App层面开启TLS 1.2是对外的网络配置,不影响内部兼容会话的协议设置。
解决方案
方案一:在兼容会话中单独配置TLS 1.2
通过Invoke-Command直接在WinPSCompatSession中设置TLS协议,再加载模块:
# 先在兼容会话中强制启用TLS 1.2 Invoke-Command -Session (Get-PSSession WinPSCompatSession) { [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 } # 再加载目标模块 Import-Module $PSScriptRoot\Modules\NTware.Ufo.PowerShell.ObjectManagement.dll -UseWindowsPowerShell
方案二:尝试跳过版本检查直接加载模块(优先测试)
根据警告提示,尝试使用-SkipEditionCheck参数直接在PowerShell Core中加载模块,避免使用兼容会话:
# 主会话中设置TLS 1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # 跳过版本检查加载模块 Import-Module $PSScriptRoot\Modules\NTware.Ufo.PowerShell.ObjectManagement.dll -SkipEditionCheck
注意:如果模块依赖Windows PowerShell专属API(如某些.NET Framework组件),此方法可能失败,需测试验证。
方案三:验证兼容会话的TLS设置
可以执行以下命令确认兼容会话当前的安全协议配置:
Invoke-Command -Session (Get-PSSession WinPSCompatSession) { [Net.ServicePointManager]::SecurityProtocol }
如果返回结果不包含Tls12,说明方案一的配置是必要的。
内容的提问来源于stack exchange,提问作者user3565039
相关产品推荐
相关产品推荐

