Public/Invoke-SfExecuteApex.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
<#
    .SYNOPSIS
    Execute anonoymous apex in the configured Salesforce org

    .DESCRIPTION
    Execute anonoymous apex in the configured Salesforce org

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

    .OUTPUTS
    None. Throws error if the apex either fails to compile or the result is not 'success'

    .PARAMETER Apex
    The anonymous apex to execute.

    .EXAMPLE
    PS> Invoke-SfExecuteApex "phecc.TriggerHandlers.setEnabled(false, new List<String> {'ObservationBD' });"

    .LINK
    Set-Config

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

function Invoke-SfExecuteApex {

    [CmdletBinding()]
    [OutputType([System.Void])]
    param(
        [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Apex
    )
    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)"

        $encodedURL = [System.Web.HttpUtility]::UrlEncode($Apex)
        $result = (Invoke-SfApi "/tooling/executeAnonymous/?anonymousBody=$($encodedURL)")
        if ($result.compiled -ne 'True') {
            throw "Apex compile failed: $($result.compileProblem)-$($result.exceptionMessage) line:$($result.line), column: $($result.column)"
        }
        if ($result.success -ne 'True') {
            throw "Apex execution failed: $($result.exceptionMessage)-$($result.exceptionMessage)"
        }
    }
}