How can I introduce a config file to Powershell scripts?

pencilCake picture pencilCake · Dec 4, 2012 · Viewed 35.4k times · Source

Assume that I have a Powershell script called Foo.ps1

I would like to introduce an XML configuration file called Foo.ps1.config

where I can specify my environment settings something like:

<FunctionsDirectory>
     $ScriptDirectory\Functions
</FunctionsDirectory>
<ModulesDirectory>
     $ScriptDirectory\Modules
</ModulesDirectory>

And then I would like to load this configuration in the begining of Foo.ps1 so that I can import my modules and dot notate to the Functions directory.

How can I achieve this in Powershell?

Answer

John Collins picture John Collins · Feb 2, 2014

Probably an easier solution.... Assuming your configuration file is names "Confix.xml", try this:

PS Testing> [xml]$configFile= get-content .\Config=.xml
PS Testing> $configFile
xml                                  configuration
---                                  -------------
version="1.0"                        configuration

Reading data out of your new variable:

PS Testing> $configFile.configuration.appsettings
#comment                             add
--------                             ---
Vars                                 {add, add}

PS Testing> $configFile.configuration.appsettings.add
key                                  value
---                                  -----
var1                                 variableValue1
var2                                 variableValue2

PS Testing> $configFile.configuration.appsettings.add[0].value
variableValue2

Long story short: Cast your variable as XML, and do a get-content.

In this case, the Config.xml looks like this:

<?xml version="1.0"?>
<configuration>
  <startup>
  </startup>
  <appSettings>
    <!--Vars -->
    <add key="var1" value="variableValue1"/>
    <add key="var2" value="variableValue2"/>
  </appSettings>
</configuration>