14

Is it possible to use a configuration file with a PowerShell script?

For example, the configuration file:

#links
link1=http://www.google.com
link2=http://www.apple.com
link3=http://www.microsoft.com

And then call this information in the PS1 script:

start-process iexplore.exe $Link1
17

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").*

  • 4
    You can also get the settings out by the much friendlier $h.MySetting1 – Ryan Shillington Nov 13 '15 at 19:54
  • I get an array out of bounds exception in the regex parser line, despite using the exact same .txt file shown in this answer and the parser code (no changes) => Index was outside the bounds of the array. At C:\testConfigreader.ps1:13 char:264 + ... -ne $True)) { $h.Add($k[0], $k[1]) } } + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OperationStopped: (:) [], IndexOutOfRangeException + FullyQualifiedErrorId : System.IndexOutOfRangeException Does anyone have this working correctly? – Shiva Mar 9 '17 at 0:24
  • If you config file don't have [Sections] or ; semicolon comments, you can do just $config = Get-Content $ConfigPath | ConvertFrom-StringData. See ConvertFrom-StringData for details. – asmironov Jun 8 '19 at 20:40
4

There's a good thread here which shows this code (quoting from the linked thread):

# from http://www.eggheadcafe.com/software/aspnet/30358576/powershell-and-ini-files.aspx
param ($file)

$ini = @{}
switch -regex -file $file
{
    "^\[(.+)\]$" {
        $section = $matches[1]
        $ini[$section] = @{}
    }
    "(.+)=(.+)" {
        $name,$value = $matches[1..2]
        $ini[$section][$name] = $value
    }
}
$ini

Then you can do:

PS> $links = import-ini links.ini
PS> $links["search-engines"]["link1"]
http://www.google.com
PS> $links["vendors"]["link1"]
http://www.apple.com

Assuming an INI file that looks like this:

[vendors]
link1=http://www.apple.com
[search-engines]
link1=http://www.google.com

Unfortunately the regexes are missing from the code at the link so you'll have to reproduce them, but there's a version that handles files without section headers and lines that are comments.

  • You can handle comments easily by just adding another case to the switch with '^#' {}. Also you can access hashtable contents with a dot as well, so $links.vendors.link1 should work too which might be a little better to read. – Joey Oct 20 '10 at 7:20
2

yes, the cmdlets you're looking for are get-content and select-string.

$content=get-content C:\links.txt
start-process iexplore.exe $content[0]
0

For a more comprehensive approach, consider https://github.com/alekdavis/ConfigFile . This module supports config files in JSON format, as well as INI. It allows expanding variables and does a few neat tricks. The thing to remember is that the names of the key-value pairs in the INI file must match the names of the script parameters or variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.