Simple Replacement for INI Files

by Aug 14, 2015

If you'd like to keep settings outside of your script and store them in a separate config file, then you can use all kinds of data formats for it.

INI files lack native support so you would have to parse them manually. JSON and XML have parsers but produce too complex text that is not easily maintained by mortals.

If your config data can be expressed as key-value pairs like below, then we have an alternative:

Name = 'Tom'
ID = 12
Path = 'C:'

Save the key-value pairs to a plain text file, then use this code to read the file:

$hashtable = @{}
$path = 'z:\yourfilename.config'

$payload = Get-Content -Path $path |
Where-Object { $_ -like '*=*' } |
ForEach-Object {
    $infos = $_ -split '='
    $key = $infos[0].Trim()
    $value = $infos[1].Trim()
    $hashtable.$key = $value
}

The result is a hash table, and you can easily access the values like this:

$hashtable.Name
$hashtable.ID
$hashtable.Path

Twitter This Tip! ReTweet this Tip!