XML is a great way to create configuration files for complex PowerShell scripts. Reading environment variables from such a configuration files is a little tricky, though.
To demonstrate how environment variables can be read from XML files, I have created the following, very simple XML file.
It includes two directories. One is specified by an environment variable (%WINDIR%) – the other just by a full path.
Note:
I included this second directory to demonstrate that using the explained method does not require to specify an environment variables – yet it’s optional.
Directories.xml
<?xmlversion="1.0"encoding="utf-8"?>
<directories>
<directory>%WINDIR%</directory>
<directory>C:\Temp</directory>
</directories>
ReadEnvFromXml.ps1
[xml]$paths = Get-Content .\Directories.xml;
Write-Host -ForegroundColor Red "Environment Variables not resolved:";
$paths.SelectNodes("/directories/directory") | ForEach-Object{ Write-Host $_.'#text' };
Write-host -ForegroundColor Green "Environment Variables resolved:";
$paths.SelectNodes("/directories/directory") | ForEach-Object{ Write-Host ([System.Environment]::ExpandEnvironmentVariables($_.'#text')) };
This script reads the XML file and selects the directory nodes by using XPath.
The essential part of this demo is the second section were the method [System.Environment]::ExpandEnvironmentVariables() gets invoked. This static .NET method replaces the name of each environment variable with the string equivalent of the value of the variable.
You can see, that if you don’t use this method, the environment variable will not expand.
Note:
Also specifying the environment variable in the PowerShell syntax ($Env:windir) will not expand the variable if read from a file.