为什么PowerShell无法发送适当的Crumb?

时间:2017-09-09 14:53:26

标签: powershell jenkins

我的PowerShell脚本:

$Params = @{
    uri     = "http://${API_URL}:${API_Port}/crumbIssuer/api/json";
    Method  = 'Get';
    Headers = @{
        Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${API_User}):$(${API_Pass})"));
    }
}

$API_Crumb = Invoke-RestMethod @Params

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Jenkins-Crumb", $API_Crumb.Crumb)

$Params = @{
    uri     = "http://${API_URL}:${API_Port}/job/${API_Job}/build";
    Method  = 'Post';
    Headers = $headers;
}

Invoke-RestMethod @Params

错误:

  

请求中未包含有效的crumb

1 个答案:

答案 0 :(得分:5)

我按如下方式修改了代码并且工作正常。不确定为什么以前的代码会抛出错误。

$API_User = "admin"
$API_Pass = "password"
$API_URL = "localhost"
$API_Port = "8080"
$API_Job = "test01"

$h = @{}
$h.Add('Authorization', 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$(${API_User}):$(${API_Pass})")))

$Params = @{uri = "http://${API_URL}:${API_Port}/crumbIssuer/api/json";
        Method = 'Get';
        Headers = $h;}
$API_Crumb = Invoke-RestMethod @Params

$h.Add('Jenkins-Crumb', $API_Crumb.crumb)
$Params['uri'] = "http://${API_URL}:${API_Port}/job/${API_Job}/build"
$Params['Method'] = 'Post'
$Params['Headers'] = $h

Invoke-RestMethod @Params