Public/Invoke-SfApi.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
<#
    .SYNOPSIS
    Invokes a Salesforce API endpoint for the currently configured org.

    .DESCRIPTION
    Invokes a Salesforce API endpoint for the currently configured org.

    .INPUTS
    None. You cannot pipe objects to Invoke-SfApi.

    .OUTPUTS
    Returns as PSCustomObject with the format of the API being called. (Depends on use)

    .PARAMETER Path
    The path portion beyond "/services/data" to use.

    .PARAMETER Version
    The version of the API to use. The default is 48.0

    .PARAMETER Method
    The method to call. Get,Post,Delete,Put. The default is "Get"

    .PARAMETER Body
    The body to pass to the method

    .EXAMPLE
    PS> $patientIds = (Invoke-SfApi "/query?q=SELECT+Id+FROM+phecc__Patient__c").records | Select Id

    .LINK
    Set-Config

    .NOTES
    Assumes config is initialized for org access.
#>

function Invoke-SfApi {

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Path,

        [Parameter(Mandatory = $false, Position = 1)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Version = "48.0",

        [Parameter(Mandatory = $false, Position = 2)]
        [ValidateSet('Get', 'Post', 'Delete', 'Put', 'Patch')]
        $Method = "Get",

        [Parameter(Mandatory = $false, Position = 3)]
        [ValidateNotNullOrEmpty()]
        [String]$Body
    )
    begin {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Function started"
    }

    end {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Complete"
    }

    process {
        Write-Debug "[$($MyInvocation.MyCommand.Name)] PSBoundParameters: $($PSBoundParameters | Out-String)"

        $orgUrl = $script:__sfAuth.instance_url
        $headers = Get-SfHeaders
        $services = Invoke-RestMethod -Uri "$($orgUrl)/services/data" -Method Get
        $dataUrl = ($services | Where-Object { $_.version -eq $version }).url
        Write-Debug $dataUrl
        $dataFullUrl = "$($orgUrl)$($dataUrl)"
        $url = "$($dataFullUrl)$($path)"
        $headers.Add("Content-Type", "application/json")
        Write-Debug "Invoke-RestMethod -Uri $($url) -Method $($Method)"
        Write-Debug "Headers: $($headers | ConvertTo-Json -Depth 100)"
        Write-Debug "Body: $($body | ConvertTo-Json -Depth 100)"
        Invoke-RestMethod -Uri $url -Method $Method -Headers $headers -Body $Body
    }
}