abh*_*i88 5 powershell yaml powershell-3.0 apiconnect
我想在 PowerShell 文件中解析来自 IBM API Connect 的 YAML 文件。我将无法放置第三方包或 DLL,因为安全审查不会同意它。
---
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"
Run Code Online (Sandbox Code Playgroud)
我只想获取与它相关联的 API YAML 文件,我已经用谷歌搜索并开发了一个实际运行的示例 PowerShell 代码。
$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
Run Code Online (Sandbox Code Playgroud)
有没有什么简单的方法可以实现这一点,而不是在字符串中进行多次替换?
我建议在本地分叉一个新的可用 powershell 模块:PowerShell CmdLets for YAML 格式操作。
此 powershell 模块是 YamlDotNet 之上的一个薄包装器,用于将简单的 powershell 对象序列化到 YAML 或从 YAML 反序列化。它在 powershell 版本 4 和 5 上进行了测试,支持 Nano Server,并且显然可以在 Linux 上与 powershell 配合使用。我怀疑它在 Mac 上也能工作,但我还没有机会测试它。
该模块提供ConvertFrom-Yaml
解析yaml的命令。
$text = @"
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"
"@
Run Code Online (Sandbox Code Playgroud)
Import-Module powershell-yaml
$yaml = ConvertFrom-Yaml $text
foreach ($api in $yaml.apis.GetEnumerator()) {
Write-Host "$($api.Name) ref: $($api.Value['$ref'])"
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12895 次 |
最近记录: |