Skip to content

Instantly share code, notes, and snippets.

@mark05e
Last active May 13, 2024 12:08
Show Gist options
  • Save mark05e/6cf4b3dda15b66431db405a6ce53496d to your computer and use it in GitHub Desktop.
Save mark05e/6cf4b3dda15b66431db405a6ce53496d to your computer and use it in GitHub Desktop.
Reads an INI file and parses it into a hashtable structure. From https://stackoverflow.com/questions/43690336/powershell-to-read-single-value-from-simple-ini-file
# https://stackoverflow.com/questions/43690336/powershell-to-read-single-value-from-simple-ini-file
function Get-IniFile
{
param(
# Required parameter specifying the path to the INI file.
[parameter(Mandatory = $true)] [string] $filePath
)
$anonymous = "NoSection"
$ini = @{}
# Use switch statement with regular expressions to process lines in the file
switch -regex -file $filePath
{
# Line starting with '[' defines a new section
"^\[(.+)\]$" # Section
{
# Capture the section name from the match
$section = $matches[1]
# Create a new hashtable for this section within the main hashtable
$ini[$section] = @{}
# Initialize a counter for comments within this section
$CommentCount = 0
}
# Line starting with ';' is considered a comment
"^(;.*)$" # Comment
{
# If no section is currently defined, use a temporary 'NoSection' section
if (!($section))
{
$section = $anonymous
$ini[$section] = @{}
}
# Capture the comment text from the match
$value = $matches[1]
# Increment the comment counter
$CommentCount = $CommentCount + 1
# Create a unique name for the comment based on the counter
$name = "Comment" + $CommentCount
# Add the comment to the section's hashtable
$ini[$section][$name] = $value
}
# Line with a key-value pair separated by '='
"(.+?)\s*=\s*(.*)" # Key
{
# If no section is currently defined, use a temporary 'NoSection' section
if (!($section))
{
$section = $anonymous
$ini[$section] = @{}
}
# Capture the key and value from the match using indexing
$name,$value = $matches[1..2]
# Add the key-value pair to the section's hashtable
$ini[$section][$name] = $value
}
}
return $ini
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment