Last active
July 31, 2024 01:03
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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