PoshCode Archive  Artifact [a917edd8b5]

Artifact a917edd8b5b3cc451abfa7ea8f374e86876b94708057649a401c329e1194da13:

  • File Get-Labels.ps1 — part of check-in [18a28be982] at 2018-06-10 13:37:25 on branch trunk — Pulls label-value pairs from text. Note that this version is REALLY, REALLY optimistic, and assumes that your label-value pairs are each, always, on their own line. (user: Joel Bennett size: 1737)

# encoding: ascii
# api: powershell
# title: Get-Labels
# description: Pulls label-value pairs from text. Note that this version is REALLY, REALLY optimistic, and assumes that your label-value pairs are each, always, on their own line.
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Get-Label
# x-poshcode-id: 4142
# x-derived-from-id: 4143
# x-archived: 2015-05-03T19:03:30
# x-published: 2015-05-02T17:42:00
#
#
function Get-Label {
    #.Synopsis
    #   Get labelled data using Regex
    #.Example
    #   openssl.exe crl -in .\CSC3-2010.crl -inform der -text | Get-Label "Serial Number:" "Revocation Date:"
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [AllowEmptyString()]
        [string]$data,

        [Parameter(ValueFromRemainingArguments=$true)]
        [string[]]$labels = ("Serial Number:","Revocation Date:")
    )
    begin {
        [string[]]$FullData = $data
    }
    process {
        [string[]]$FullData += $data
    }

    end {
        $data = $FullData -join "`n"

        $names = $labels -replace "\s+" -replace "\W"

        $re = "(?m)" + (@(
            for($l=0; $l -lt $labels.Count; $l++) {
                $label = $labels[$l]
                $name = $names[$l]
                "$label\s*(?<$name>.*)\s*`$"
            }) -join "|")
        write-host $re
        $re = [Regex]$re

        $matches = $re.Matches($data)    
        foreach($match in $matches | where Success) {
            foreach($name in $names) {
                if($match.Groups[$name].Value) {
                    @{$name = $match.Groups[$name].Value}
                }
            }
        }
    }
}