Config files for Powershell

I had a .ps script, that used .NET ConfigurationManager for reading a .NET config file. Of some unknown reason I couln’t get the ConfigurationManager working, so I converted the the xml parser to clean powershell

The config file – setup.config:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<configuration>
	<appSettings>
		<add key="SomeKey" value="SomeValue" />
	</appSettings>
</configuration>

Powershell reading setup.config using .NET2.0 ConfigurationManager

#Using .NET ConfigurationManager:
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Configuration")
$configPath = $(Get-Location).Path + "\setup.config"
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $configPath)
$someValue = [System.Configuration.ConfigurationManager]::AppSettings["SomeKey"]

Powershell reading setup.config without ConfigurationManager

#Using Powershell only:
$configPath = $(Get-Location).Path + "\setup.config"
[xml]$configXml = Get-Content $configPath
[string]$someValue = $($configXml.configuration.appSettings.add | where { $_.key -eq "SomeKey" }).value
[bool]$someValueBool = [System.Convert]::ToBoolean($someValue)

If someone has a clue why the ConfigurationManager did not work in my environment please leave a comment.
The End

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: