Reputation: 119
How can i get variables from a config file in XML ?
I am actualy doing this using a .txt config file.
There is my actual code :
Config.txt
[Repertoire de SPO (generalement C:\SPO)]
destinationn="C:\SPO"
[Nom du sous repertoire de SPO (generalement : SPO1)]
sous_destination="SPO1"
[Numero de la version de SPO vers laquelle vous souhaitez upgrade (par exemple : 1812.4)]
version="1812.4"
[Nom du pool dapplication lie a SPO (par defaut SPO_ADV)]
applicationPoolName="SPO_ADV"
[Chemin de livraison de la nouvelle version de SPO (par defaut \\path\to\somewhere)]
livraisonn="\\path\to\somewhere"
Powershell.ps1
Get-Content "$current_path\config.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]) } }
$destinationn = $h.Get_Item("destinationn")
I would like to do a similar thing using an .xml config file.
Upvotes: 9
Views: 21805
Reputation: 591
This is a follow up to HariHaran's post. My connection.config file had the same elements and structure as his, but my working code is slightly different.
Use this to load the xml object
$appConfig = New-Object XML
$appConfig.Load($appConfigFile)
or use this
[xml]$appConfig = Get-Content $appConfigFile
and here is the working code to get the connection string
foreach ($xmlAddElement in $appConfig.connectionStrings.add) {
$connectionString = $xmlAddElement.connectionString
Write-Host "$connectionString"
}
Upvotes: 1
Reputation: 9143
Xml is much easier to parse with PowerShell. See following example with comments:
#Translated XML config
@'
<root>
<destinationn>C:\SPO</destinationn>
<sous_destination>SPO1</sous_destination>
<version>1812.4</version>
<applicationPoolName>SPO_ADV</applicationPoolName>
<livraisonn>\\path\to\somewhere</livraisonn>
</root>
'@ | Out-File YourSampleConfig.xml
#read xml file, skip root
$config = ([xml](Get-Content YourSampleConfig.xml)).root
#get <destinationn> value
$config.destinationn
Upvotes: 12
Reputation: 4119
$appConfigFile = [IO.Path]::Combine($currentDirectory, '.\MyFile.config')
$appConfig = New-Object XML
$appConfig.Load($appConfigFile)
foreach ($connectionString in $appConfig.configuration.connectionStrings.add) {
# Get the connection string
$dbconnectionstring = $connectionString.connectionString
}
Here's my config xml
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="AtomicScopeConStr" connectionString="Server= localhost; Database= mydatabase; Integrated Security=True;" />
</connectionStrings>
<appSettings>
</appSettings>
</configuration>
Upvotes: 3