如何在Windows PowerShell中使用curl设置cookie完成TestRail身份验证
报错根因
你遇到的参数不识别报错,是因为PowerShell中默认的curl是Invoke-WebRequest cmdlet的别名,并不支持原生curl的--cookie-jar、-user等参数,才会抛出对应错误。
解决方案
方案1:使用原生curl工具(推荐,兼容原有命令写法)
Windows 10 1809及以上版本默认自带原生curl二进制,你只需要把命令里的curl改成curl.exe即可走原生curl逻辑:
- 登录并保存cookie到本地
curl.exe -u username:password --cookie-jar cookie.txt https://testrail01.ando.pay1-test.de/index.php?/auth/login
- 调用获取项目接口时携带本地cookie
curl.exe --cookie cookie.txt https://testrail01.ando.pay1-test.de/index.php?/api/v2/get_projects
方案2:直接在API请求中携带认证信息(无需处理cookie)
TestRail的API支持直接在请求中带Basic Auth认证,不需要先请求登录接口存cookie,可以直接调用业务接口:
curl.exe -u username:password https://testrail01.ando.pay1-test.de/index.php?/api/v2/get_projects
方案3:使用PowerShell原生语法实现(无需额外安装curl)
如果你不想用原生curl,可以直接用PowerShell的Invoke-WebRequest语法实现相同逻辑:
# 构造Basic Auth认证头 $auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("username:password")) $headers = @{ Authorization = "Basic $auth" } # 方式一:直接调用接口,无需处理cookie $projects = Invoke-WebRequest -Uri "https://testrail01.ando.pay1-test.de/index.php?/api/v2/get_projects" -Headers $headers $projects.Content # 方式二:必须用cookie会话的场景 # 登录并保存会话 Invoke-WebRequest -Uri "https://testrail01.ando.pay1-test.de/index.php?/auth/login" -Headers $headers -SessionVariable trSession # 携带会话调用接口 $projects = Invoke-WebRequest -Uri "https://testrail01.ando.pay1-test.de/index.php?/api/v2/get_projects" -WebSession $trSession $projects.Content
注意事项
- 生产环境不要硬编码明文账号密码,建议用环境变量、加密配置或者TestRail提供的API密钥代替密码使用
- 如果调用时出现SSL证书问题,可以在curl命令后加
-k参数跳过证书校验,PowerShell 6及以上版本可以加-SkipCertificateCheck参数
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

