I'm trying to find a toml file parser in powershell, but I can't find any info about it in powershellgallery.
CodePudding user response:
Indeed, as of this writing, there seems to be no PowerShell module for TOML parsing published in the PowerShell Gallery:
- Searching for "TOML" yields no relevant matches as of this writing.
However, there is a .NET package available in the NuGet Gallery:
While you can consume NuGet packages from PowerShell, doing so is nontrivial as of PowerShell Core 7.2.2, unfortunately.
This answer discusses the current pitfalls and potential future enhancements.
In this particular case, because the package has no dependencies, you can get away with downloading the package via
Install-Package
, as shown below:
Sample use:
# 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']
Note:
With with dictionary types, PowerShell usually allows interchangeable use of index syntax (e.g.
['my_table']
) and dot notation , via.
, the member-access operator (e.g..my_table
).However, dot notation is not supported for the dictionaries of type
[Tomlyn.Model.Table]
, such as returned by[Tomlyn.Toml]::ToModel()
, presumably because that type only implements the genericIDictionary`2
interface, and not also its non-generic counterpart,IDictionary
.- See GitHub issue #17190 for a discussion.