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

GitLab流水线执行PowerShell冒烟测试脚本遇CS0246错误求助

解决方案:PowerShell脚本兼容GitLab流水线(PS7)或强制使用PS5.1

问题根源

你的脚本在PowerShell 5.1(基于.NET Framework)正常运行,但在PowerShell 7.2(基于.NET Core/.NET 5+)报错,核心原因:

  • .NET Core移除了System.Net.ICertificatePolicy接口,这是第一个错误的直接诱因
  • PowerShell 7默认禁用旧版安全协议(Ssl3、Tls1.0、Tls1.1),导致修改证书验证回调后出现协议不支持的错误

Option 1:修改脚本兼容PowerShell 7.2

替换旧的证书验证逻辑和安全协议设置,适配.NET Core环境:

修改后的完整代码

# 替换ICertificatePolicy为.NET Core支持的证书验证回调
add-type @"
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class TrustAllCerts {
    public static void SetPolicy() {
        ServicePointManager.ServerCertificateCustomValidationCallback = 
            (sender, cert, chain, sslPolicyErrors) => true;
    }
}
"@

# 设置PowerShell 7支持的安全协议(仅保留Tls1.2及以上版本)
$AllProtocols = [System.Net.SecurityProtocolType]::Tls12 -bor [System.Net.SecurityProtocolType]::Tls13
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[TrustAllCerts]::SetPolicy()

$HTTP_Status_Timeout = 0
$HTTP_Request = [System.Net.WebRequest]::Create($url)

关键修改说明

  1. 证书验证逻辑:用ServerCertificateCustomValidationCallback替代已废弃的ICertificatePolicy,这是.NET Core官方推荐的证书验证方式
  2. 安全协议:仅保留Tls1.2和Tls1.3,避免指定PowerShell 7默认禁用的旧协议(Ssl3、Tls1.0、Tls1.1)
  3. 若必须兼容仅支持旧协议的服务,需先在系统层面启用对应协议,但存在安全风险,不推荐

Option 2:强制GitLab流水线使用PowerShell 5.1

之前的#Requires -Version 5.0无效,是因为GitLab runner默认用pwsh(PowerShell 7启动器)执行脚本,需明确指定用powershell.exe(PowerShell 5.1启动器):

修改.gitlab-ci.yml配置

在流水线job中,将脚本执行方式改为调用powershell.exe:

smoke-test-job:
  stage: test
  script:
    # 直接执行命令
    - powershell.exe -Command "& {你的脚本内容}"
    # 或者执行脚本文件
    - powershell.exe -File ./smoke-test-script.ps1
  tags:
    - windows-runner # 确保runner是Windows环境,自带PS5.1

注意事项

  • 确保GitLab runner为Windows环境(Linux runner无powershell.exe)
  • 脚本开头可保留#Requires -Version 5.0,防止被PS7意外执行

你之前尝试无效的原因

  1. -SkipCertificateCheck无效:该参数是Invoke-WebRequest/Invoke-RestMethod的专属参数,你使用的是底层System.Net.WebRequest,因此不生效
  2. #Requires -Version 5.0无效:GitLab runner若通过pwsh启动脚本,只会抛出版本不兼容错误,不会自动切换到PS5.1,必须显式指定powershell.exe

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:05:46