我正在尝试寻找适用于 PowerShell 的 TOML 文件解析器。
我在 PowerShell Gallery 或预装的 PowerShell 功能中找不到任何有关它的信息。
事实上,截至撰写本文时,PowerShell Gallery中似乎还没有用于 TOML 解析的 PowerShell 模块:
但是,NuGet Gallery中有一个可用的.NET包:
可以使用 PowerShell 中的 NuGet 包,但不幸的是,从 PowerShell Core 7.2.2 开始,这样做并不简单。
# Determine the package's local installation location.
# If it isn't installed, install it first, in the current user's scope.
while (-not ($installDir = (Get-Package -ErrorAction Ignore -ProviderName NuGet Tomlyn).Source)) {
$null = Install-Package -Scope CurrentUser -ErrorAction Stop -ProviderName NuGet Tomlyn
}
# Load the package's assembly into the session.
Add-Type -ErrorAction Stop -LiteralPath (Join-Path $installDir '../lib/netstandard2.0/Tomlyn.dll')
# Define a sample TOML string to parse.
$tomlStr = @'
global = "this is a string"
# This is a comment of a table
[my_table]
key = 1 # Comment a key
value = true
list = [4, 5, 6]
'@
# Parse the TOML string into an object mod)el (nested dictionaries).
$tomlTable = [Tomlyn.Toml]::ToModel($tomlStr)
# Output the '[my_table]' section's 'list' value.
# -> 4, 5, 6
# IMPORTANT: Use ['<key>'] syntax; .<key> syntax does NOT work.
$tomlTable['my_table']['list']
注:
对于字典类型,PowerShell
通常https://github.com/jborean93/PSToml