Public/Add-MessagesToOrg.ps1

<#
    .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
        $sfAuthenticate = $script:__sfAuth
        $headers = Get-SfHeaders
        $headers."Content-Language" = "en-US"
        $headers."Version" = $config.SalesforcePostObsApiVersion
        $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)"
        }
    }
}