Private/Split-PemChain.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
function Split-PemChain {
    [CmdletBinding(DefaultParameterSetName='FromFile')]
    param(
        [Parameter(ParameterSetName='FromFile',Mandatory,Position=0)]
        [string]$ChainFile,
        [Parameter(ParameterSetName='FromBytes',Mandatory,Position=0)]
        [byte[]]$ChainBytes
    )

    if ('FromFile' -eq $PSCmdlet.ParameterSetName) {
        # resolve relative path
        $ChainFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($ChainFile)
        $chainLines = Get-Content $ChainFile
    } else {
        # encode the bytes and split on the newlines
        $chainLines = [Text.Encoding]::ASCII.GetString($ChainBytes).Split("`n")
    }

    $PEM_BEGIN = '-----BEGIN *'
    $PEM_END   = '-----END *'

    for ($i=0; $i -lt $chainLines.Count; $i++) {
        if ($chainLines[$i] -like $PEM_BEGIN) {
            $iStart = $i
            continue
        }
        if ($chainLines[$i] -like $PEM_END) {
            $pemLines = $chainLines[$iStart..$i]
            Write-Output @(,$pemLines)
            continue
        }
    }

}