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

PowerShell脚本远程调用Jenkins任务遇401/403错误,求排查解决

Jenkins远程调用PowerShell脚本权限问题

我正在编写PowerShell脚本远程触发Jenkins任务并查询构建状态,但测试了30多种脚本变体后,始终遇到401 Unauthorized或403 Forbidden错误。Postman生成的基础POST请求脚本可以正常运行,但添加获取Jenkins构建状态的逻辑后就出现权限问题。我尝试过API Token、任务Token、用户名密码等多种认证方式,且Jenkins已配置允许远程请求,问题仍未解决。

出错的PowerShell脚本

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic credentials")

$user = 'user'
$pass = 'api-token'

Invoke-RestMethod 'http://jobUrl/job/jobName/buildWithParameters?DOBUILD=true&BUILD_MODE=Release&SELECT_BUILDS=ALL&BUILD_COMPONENTS=ALL' -Method 'POST' -Headers $headers

Start-Sleep -Seconds 45

$credentials = New-Object System.Management.Automation.PSCredential($user, (ConvertTo-SecureString $pass -AsPlainText -Force))

$status = Invoke-RestMethod "http://jobUrl/job/jobName/lastBuild/api/json" -Method Get -Credential $credentials

$returnStatus = $status.result

Write-Output $returnStatus

脚本错误输出

Invoke-RestMethod :
Error 401 Unauthorized
HTTP ERROR 401 Unauthorized
URI:/job/jobName/buildWithParameters
STATUS:401
MESSAGE:Unauthorized
SERVLET:Stapler
Powered by Jetty:// 10.0.16
At C:\temp\OneDrive - Teradyne\Jenkins\test3.ps1:7 char:1
+ Invoke-RestMethod 'http://jobURL/job/jobNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Invoke-RestMethod : The remote server returned an error: (403) Forbidden.
At C:\temp\OneDrive - Teradyne\Jenkins\test3.ps1:13 char:11
+ $status = Invoke-RestMethod "jobURL/job/jobNa ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Postman生成的可用基础脚本

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic credentials")

$response = Invoke-RestMethod 'http://URL/job/jobName/buildWithParameters?DOBUILD=true&BUILD_MODE=Release&SELECT_BUILDS=ALL&BUILD_COMPONENTS=ALL&UPLOAD_IMAGE=YES' -Method 'POST' -Headers $headers

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 05:13:23