powershelltoml

Is there a module for parsing TOML files in PowerShell?


I'm trying to find a TOML file parser for PowerShell.

I can't find any information about it either in PowerShell Gallery or in the preinstalled PowerShell functions.


Solution

  • Indeed, as of this writing, there seems to be no PowerShell module for TOML parsing published in the PowerShell Gallery:

    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.

    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: