目前为止,根据本文撰写的时间,似乎没有适用于 TOML 解析的 PowerShell 模块可在 PowerShell 平台上架:
不过,在 NuGet Gallery 可以找到一个 .NET 包:
虽然在 PowerShell Core 7.2.2 下让其消费 NuGet 包是可以做到的,但 并不简单。
该回答 指出当前问题和未来的可能优化。
在此情况下,因为该包没有依赖项,您可以通过 Install-Package
命令下载该包,如下所示:
使用示例:
# 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通常允许通过索引语法(例如['my_table']
)和点符号语法(例如.my_table
)进行交替使用,但这种用法对于类型为[Tomlyn.Model.Table]
的字典不受支持。这种字典是由[Tomlyn.Toml]::ToModel()
返回的,可能是因为该类型仅实现了通用的IDictionary`2
接口,而没有实现其非通用版本IDictionary
。