Use a Settings File for Your PowerShell Scripts | Quisitive
Use a Settings File for Your PowerShell Scripts
February 27, 2009
Quisitive
Read my method below

When developing scripts (and almost anything else) I prefer to hard-code any settings thay may need to be changed later. 

One method that I employ while writing PowerShell scripts is the use of a settings.ini file.  In this file I can place any configuration information and when I need to change a setting or run the script against another environment I only need to modify a single file.

Within the file I can group thing logically and assign simple values that can be used within the scripts.  When the PowerShell script runs, it will read the contents of the settings.ini file into a hashtable for easy retreival.  A hastable is good becase it provides a simple key/value pair that makes getting the values easy.

This PowerShell snippet will read the contents of an .ini style settings file into a HashTable.

Example Setting.ini

12345678910[General]MySetting1=value[Locations]InputFile=”C:Users.txt”OutputFile=”C:output.log”[Other]WaitForTime=20VerboseLogging=True

PowerShell Command

12Get-Content “C:settings.ini” | foreach-object -begin {$h=@{}} -process { $k = [regex]::split($_,’=’); if(($k[0].CompareTo(“”) -ne 0)     -and ($k[0].StartsWith(“[“) -ne $True)) { $h.Add($k[0], $k[1]) } }

*The above statement may be broken into multiple lines for web display only.

After executing the code snippet, a variable ($h) will contain the values in a HashTable.

KeyValue
MySetting1value
VerboseLoggingTrue
WaitForTime20
OutputFile“C:output.log”
InputFile“C:Users.txt”

To get an item from the table use the command

1$h.Get_Item(“MySetting1”).