How to use a config file (ini, conf,...) with a PowerShell Script?
Thanks a lot for your help Dennis and Tim! Your answers put me on the good track and I found this
SETTINGS.TXT
#from http://tlingenf.spaces.live.com/blog/cns!B1B09F516B5BAEBF!213.entry
#
[General]
MySetting1=value
[Locations]
InputFile="C:\Users.txt"
OutputFile="C:\output.log"
[Other]
WaitForTime=20
VerboseLogging=True
POWERSHELL COMMAND
#from http://tlingenf.spaces.live.com/blog/cns!B1B09F516B5BAEBF!213.entry
#
Get-Content "C:\settings.txt" | 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]) } }
then
After executing the code snippet, a variable ($h) will contain the values in a HashTable.
Name Value
---- -----
MySetting1 value
VerboseLogging True
WaitForTime 20
OutputFile "C:\output.log"
InputFile "C:\Users.txt"
*To retrieve an item from the table, use the command $h.Get_Item("MySetting1").*
There is a much more convenient way to read settings from JSON-file using the ConvertFrom-Json
Cmdlet in PowerShell to read a JSON formatted file:
$SettingsObject = Get-Content -Path \path\to\settings.json | ConvertFrom-Json
In your case settings in JSON would be like settings.json
:
{
"link1": "http://www.google.com",
"link2": "http://www.apple.com",
"link3": "http://www.microsoft.com"
}
Reading:
PS C:\> $SettingsObject = Get-Content -Path \path\to\settings.json | ConvertFrom-Json
PS C:\> $SettingsObject
link1 link2 link3
----- ----- -----
http://www.google.com http://www.apple.com http://www.microsoft.com
PS C:\> $SettingsObject.link1
http://www.google.com
Source: PowerTip: Read a JSON configuration file as a PowerShell object