Public/Convert-Sf15to18.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
<#
    .SYNOPSIS
    Converts a Salesforce 15 character identifier to 18 characters

    .DESCRIPTION

    .INPUTS
    The salesforce 15 character Id

    .OUTPUTS
    The salesforce 18 character id

    .PARAMETER Id
    The salesforce 15 character Id


    .EXAMPLE
    C:\PS> ConvertSf15To18 "a173t00000LOyZn"

    .LINK
    .NOTES
#>

function Convert-Sf15To18 {

    [CmdletBinding()]
    [OutputType([String])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Id
    )

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

        if ($Id.Length -ne 15) {
            throw "Id is not 15 characters"
        }

        $InChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"
        $InUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray() | % { [int][char]$_ }
        $SalesForceID_Rev = $Id | % { -join $_[$_.Length..0] }
        $SalesForceID_RevArray = $SalesForceID_Rev.ToCharArray() | % { [int][char]$_ }
        $Checksum = ""
        $InCnt = 0
        $pos = 15
        foreach ($Char in $SalesForceID_RevArray) {
            $InCnt = (2 * $InCnt) + $InUpper.Contains($Char)
            if ($pos % 5 -eq 1) {
                $Checksum = $InChars.Substring($InCnt, 1) + $Checksum
                $InCnt = 0
            }
            $pos = $pos - 1
        }
        Write-Output "$($Id)$($Checksum)"
    }
}