Public/Invoke-Jenkins.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
function Invoke-Jenkins {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [String] $Resource,
        [String] $Method = "GET",
        [Object] $Body,
        [Hashtable] $Form,
        [Hashtable] $Query = @{},
        [String] $ContentType = "application/json",
        [ValidateRange("NonNegative")]
        [Int] $MaximumRedirectionCount = 0,
        [String] $Username = $script:apiUsername,
        [SecureString] $Password = $script:apiPassword,
        [ValidateRange("NonNegative")]
        [int] $MaximumAttempts = 3,
        [bool] $TreatRedirectAsSucces = $true
    )
    $headers = Get-JenkinsRequestHeaders -Username $Username -Password $Password
    $request = [System.UriBuilder] "$($script:jenkinsUrl)/$Resource"
    $request.Query = Get-Params -Query $Query

    $attempts = 0

    Write-Debug "---- Invoke-Jenkins ----"
    Write-Debug "Resource: $Resource"
    Write-Debug "Request: $request"
    Write-Debug "Method: $Method"
    Write-Debug "Body: $Body"
    Write-Debug "Query: $Query"

    while ($attempts -lt $MaximumAttempts) {

        try {
            $attempts += 1
            if($null -ne $Form){
                $response = Invoke-WebRequest -Uri $Request.Uri `
                -Headers $headers `
                -Method $Method `
                -Form $Form `
                -UseBasicParsing `
                -TimeoutSec 30 `
                -ErrorAction SilentlyContinue `
                -MaximumRedirection $MaximumRedirectionCount
            }
            else {
                $response = Invoke-WebRequest -Uri $Request.Uri `
                -Headers $headers `
                -Method $Method `
                -Body $body `
                -ContentType $ContentType `
                -UseBasicParsing `
                -TimeoutSec 30 `
                -ErrorAction SilentlyContinue `
                -MaximumRedirection $MaximumRedirectionCount
            }
            Write-Debug "Response for Invoke-Jenkins: StatusCode : $($response.StatusCode), Headers: $($response.Headers), Content: $($response.Content)"
            return $response
        } catch [System.Net.Http.HttpRequestException] {
            $response = $_.Exception.Response
            if (!$response)
            {
                continue
            }

            $statusCode = $response.StatusCode.Value__
            Write-Debug "Response for Invoke-Jenkins: $($response)"
            if ($TreatRedirectAsSucces -eq $true -and $statusCode -ge 300 -and $statusCode -lt 400) {
                return $response
            } else {
                throw
            }
        }
    }
}