I want to parse an YAML file from IBM API Connect in a PowerShell file. I won't be able to put third party packages or DLLs since security review won't agree with it.
---
product: "1.0.0"
info:
name: "api2product"
title: "API2product"
version: "1.0.0"
visibility:
view:
enabled: true
type: "public"
tags: []
orgs: []
subscribe:
enabled: true
type: "authenticated"
tags: []
orgs: []
apis:
api1:
$ref: "api1_1.0.0.yaml"
api2:
$ref: "api2_1.0.0.yaml"
api3:
$ref: "api3_1.0.0.yaml"
api4:
$ref: "api4_1.0.0.yaml"
api5:
$ref: "api5_1.0.0.yaml"
plans:
default:
title: "Default Plan"
description: "Default Plan"
approval: false
rate-limit:
hard-limit: false
value: "100/hour"
I am interested to get only the API YAML files associated with it for which I have googled and developed a sample PowerShell code which is actually running.
$text = Get-Content -Path "C:\Users\abhi\Desktop\projects\TRYG\GitLab\APIPOC\test.yaml"
$regex = '(?ms)apis:(.+?)plans:'
$text = $text -join "`n"
$OutputText = [regex]::Matches($text, $regex) |
foreach {$_.Groups[1].Value -split $regex}
$OutputText = $OutputText.Replace("`$ref:", "")
$OutputText = $OutputText.Replace(":", "=")
$OutputText = $OutputText.Replace("=`n", "=")
$OutputText = $OutputText.Replace("`"", "")
$AppProps = ConvertFrom-StringData ($OutputText)
$AppProps.GetEnumerator() | ForEach-Object {$_.Value}
[string[]]$l_array = $AppProps.Values | Out-String -Stream
Is there any simple way to achieve this instead of multiple replacements in the string?
ConvertFrom-StringData
processes a list of simple key/value pairs into a hashtable. Can you get your input data in JSON format instead of YAML? PowerShell comes with a parser for the former. – Practicalpython -c 'import sys, yaml, json; json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)' < file.yaml > file.json
You will need PyYAML installed but this should work. – Whalen