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
<#
    .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 PSObjects 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 @([PSObject]@{ endpoint = "/services/apexrest/foo"; body = [PSObject]@{ value = "1" } })

    .LINK
    Set-FileConfig

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

function Add-MessagesToOrg {
    param(
        $Messages
    )

    process {
        $sfAuthenticate = Invoke-SfAuthenticate
        $headers = Get-SfHeaders $sfAuthenticate
        $headers."Content-Language" = "en-US"
        $headers."Version" = "5"
        $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)"
        }
    }
}