Functions/Invoke-ArtifactoryRestApi.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<#PSScriptInfo
 
.VERSION 1.0.0
 
.GUID
 
.AUTHOR Artsiom Krot
 
.PROJECTURI https://github.com/artyom-krot/PS.JfrogArtifactory
 
.RELEASENOTES
 
 
Script file name:
 
    Invoke-ArtifactoryRestApi.ps1
 
.DESCRIPTION
 
    The script is an integral part of PS.JfrogArtifactory solution (https://github.com/artyom-krot/PS.JfrogArtifactory)
 
#>




function Invoke-ArtifactoryRestApi {
    <#
    .SYNOPSIS
        PowerShell script for invoking rest api calls to Jfrog Artifactory.
         
        Jfrog reference documentation about rest api functionality:
        https://www.jfrog.com/confluence/display/JFROG/Artifactory+REST+API
 
    .DESCRIPTION
         
         
    .INPUTS
        -RestApiPath <string[]>
 
        -Method <[Get], [Post], [Put], [Delete]>
 
        -ContentType <string[]>
         
    .OUTPUTS
        Web response content from Jfrog Artifactory api in JSON format
 
    .NOTES
         
     
    .EXAMPLE
        Invoke-ArtifactoryRestApi -RestApiPath '/api/storageinfo' -Method Get -ContentType 'application/json'
     
        Invoke-ArtifactoryRestApi -RestApiPath '/docker/dockerimagename/dockertag1.2.3' -Method Delete
 
    #>


    [CmdletBinding()]
    param(
        [parameter(Position = 0, Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $RestApiPath,

        [parameter(Position = 1, Mandatory = $false)]
        [ValidateSet('Get', 'Post', 'Put', 'Delete')]
        [string]
        $Method = 'Get',

        [parameter(Position = 2, Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [string]
        $ContentType = 'application/json'
    )

    $artifactoryParameters = Get-ArtifactoryParameters

    $authString = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($artifactoryParameters.userName):$($artifactoryParameters.userToken)"))

    $InvokeUri = "$($artifactoryParameters.serverUri)$RestApiPath"

    $Headers = @{
        Authorization = "Basic $authString"
        Accept        = $ContentType
    }
  
    $webContent = Invoke-WebRequest -UseBasicParsing `
                                    -Uri $InvokeUri `
                                    -Headers $Headers `
                                    -Method $Method | Select-Object -ExpandProperty Content | ConvertFrom-Json
    
    return $webContent
}