I'm trying to use Powershell to read a file which is in a pseudo toml format:
[paths]
path_one="\root\project=six"
path_two="\root\project=wonderland"
[creds]
username_one="slipperyfish"
username_two="bigkahuna"
[vals]
min_level=40
min_level=90
So nothing too complicated or special.
I start by creating a new [PSCustomObject] $config variable.
What I have then been trying to do - and this might be a sub-optimal approach, is to do a switch -regex through the file content, line by line.
When I find a [section] line I initialise a new hashtable for the subsequent values to be broken into key value pairs and stored in.
Then, when I come across a '^$', or an empty line, I then want to do something like:
add-member -inputobject $config -notepropertyname $<hashtable_name> -notepropertyvalue $<hashtable_name> -force
This way all the hashtables that get built up from each [section] and its key/value pairs then get pushed into the pscustomobject which I can then use later in the script to access those values when needed.
The problem I have is that I need the new hashtables to be the name of the [section] so that when I then work with the PSCustomObject at the end it actually contains the hierarchy/properties as per the file.
How can I create a hashtables with the dynamic, only know when read, names of the sections?
Would greatly appreciate any assistance.
PS - I realise that for config/ini files in Powershell using psd1 files is a safer bet - it just happens that for this example I kind of need to use what's being supplied.
::Additional content to show where I am having the problem:
$file = "$($PSScriptRoot)\config.ini"
# Initialise the base config object:
$config = [pscustomobject]::new()
# iterate over the config file:
switch -regex ( get-content -path $file ) {
# [section] line found
'^\[.*\]$'
{
$category = $_ -replace "(\[|\])"
<#
how to create a hashtable here with NAME contained in $category variable?
This is needed so that later I can use dot notation to drill through the hashtable to
get to the values.
#>
}
}
$config.creds.username_one
<#
Should return "slipperyfish"
#>
In a nutshell, the new hashtables must have the name of the [section] to which they relate. How can I do that?
Thanks!