PowerShell funkcia pre načítanie konfigurácie z config.neon (keby niekto potreboval)

steelbull
Člen | 241
+
+1
-

Ahojte, keby niekto potreboval, posielam jednoduchý skript pre načítanie config.neon v PowerShell (v7.4).

function NetteReadNeon {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$Path,
        [bool]$Print
    )
    # Check, if file exists
    if (-Not (Test-Path -Path $Path)) {
        Write-Error "File path $Path not exists! Please correct file path."
        exit
    }
    $text = Get-Content $Path # Read file content
    $lines = $text.Split([Environment]::NewLine) # Slit content to lines
    $result = @{}
    [string[]]$lastKeys = @()
    [int32[]]$lastLevels = @()

    foreach ($line in $lines) {
        if($line.StartsWith("#") -or (-Not ($line.Contains(":")))) {
            continue # Skip comments and invalid lines
        }
        $arr = $line.Split(":");
        [int32]$level = [regex]::matches($arr[0]," ").Count + ([regex]::matches($arr[0],"`t").Count*4)
        [string]$key = $arr[0].Replace("'", "").Replace('"', "").Trim()
        [string]$value = $arr[1].Replace("'", "").Replace('"', "").Trim()
        if($value.Contains("#")) {
            $value = $value.Substring(0, $value.IndexOf('#'))
        }
        # Prefix logic (e.g. "parameters.configuration")
        if(-Not ($value) -and $key) { # If value is missing
            # Remove prefix items (lastKeys) from the end of the array when key 'lastLevel' is higher or equal to the current 'level'
            # Remove items with tmpArray and replace original array
            [string[]]$tmpLastKeys = @()
            [int32[]]$tmpLastLevels = @()
            for ($ia=0; $ia -le $lastKeys.Count-1; $ia++) {
                if($lastLevels[$ia] -lt $level) {
                    $tmpLastKeys += $lastKeys[$ia]
                    $tmpLastLevels += $lastLevels[$ia]
                }
            }
            $lastKeys = @()
            $lastKeys = $tmpLastKeys
            [int32[]]$lastLevels = @()
            $lastLevels = $tmpLastLevels
            $lastKeys += $key
            $lastLevels += $level
        }

        if($value) {
            # Generate key
            $newKey = $key
            for ($ia=$lastKeys.Count-1; $ia -gt -1; $ia--) {
                $newKey = $lastKeys[$ia]+"."+$newKey # Generate key prefix
            }
            if($Print) {
                Write-Host "$newKey = $value"
            }
            $result.$newKey = $value
        }
    }
    return $result
}

Funkciu stačí zavolať a používať napr. takto:

$config = NetteReadNeon -Path "...cesta/k/config.neon"
$dbName = $config["parameters.configuration.database.dbName"]

Editoval steelbull (30. 7. 12:36)