Use a XML-file for configuration in PowerShell scripts

Time for some PowerShell!

Almost every PowerShell script need some configuration parameters. With this post I want to show one way, there are others ;-), to parse a config file in XML format and use the values later.

The solution I’m going to show to you contains three files. A PowerShell script, a XML configuration file and a helper PowerShell file that contains a function to parse the config file.

PowerShell XML config files

The config file contains

<config>
	<hyperv dir="C:\Hyper-V\New_Server">
		<ram>2048</ram>
	</hyperv>
</config>

The helper function to parse the configuration file looks like this

# Parse Configuration file
function ParseConfig([string]$filename) {
	try {
		$file = Get-Item -Path $filename
		if ($file.Exists) {
			$root = "config"
			$cfg = [xml] ( Get-Content -Path $filename )
			return $cfg.config
		}
		else {
			Write-Host "The configuration file "$filename" does not exist" -ForegroundColor Red
		}
	}
	catch {
		Write-Host "Cannot load configuration file "$filename -ForegroundColor Red
	}
	return $null
}

And finally the main script, that will reference the helper function, call it and use the values.

# modify here
$cfgFile = "NewHyperVConfig.xml"
# stop modifying content below
# ----------------------------

# load functions from other files
. "$PSScriptRoot\helper\Configuration.ps1"

# load and parse config from xml file
$cfg = ParseConfig $PSScriptRoot"\"$cfgFile

# start doing something
Write-Host $cfg.hyperv.dir
Write-Host $cfg.hyperv.ram

Summary: Store configuration settings in a XML file and use the values in PowerShell script.