Public/Add-MessagesToOrg.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
<#
    .SYNOPSIS
    Posts message objects to a salesforce REST endpoint

    .DESCRIPTION
    Each message contains the endpoint and the body of the message to post.
    This commandlet uses Write-Progress to report activity

    .INPUTS
    Array of messages

    .OUTPUTS
    None

    .PARAMETER Messages
    An array of PSCustomObject that contain the following properties:
        - endpoint - the Salesforce API endpoint to call
        - body - PS object that represents the body to send to the endpoint. This object will be converted to JSON before post

    .EXAMPLE
    C:\PS> Add-MessageToOrg -Messages @([PSCustomObject]@{ endpoint = "/services/apexrest/foo"; body = [PSCustomObject]@{ value = "1" } })

    .LINK
    Set-Config

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

function Add-MessagesToOrg {

    [CmdletBinding()]
    [OutputType([System.Void])]
    param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline)]
        [PSCUstomObject[]]
        $Messages
    )

    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)"

        $config = Get-Config

        $version = ((Get-SfApiVersions -ApiName "ScalarRest") | Select-Object phecc__Version__c | Measure-Object -Max).Count
        Write-Debug "Using API version $($version) for ScalarRest endpoint"

        $sfAuthenticate = $script:__sfAuth
        $headers = Get-SfHeaders
        $headers."Content-Language" = "en-US"
        $headers."Version" = $version
        $i = 0
        $messages | ForEach-Object {
            $apiEndPoint = "$($sfAuthenticate.instance_url)$($_.endpoint)"
            $result = Invoke-RestMethod -Uri $apiEndPoint -Method Post -Headers $headers -Body ($_.body | ConvertTo-Json -Depth 100) -ContentType 'application/json; charset=utf-8' | ConvertFrom-Json
            if ($result.resultstatus.message -ne "Success") {
                Write-Warning "Failed to add message due to '$($result.resultstatus.message)'"
            }
            $i++
            Write-Progress -Activity "Add Messages" -PercentComplete (($i / $messages.Count) * 100) -Status "Added: $i of $($messages.Count)"
        }
    }
}