Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get variables from config file in powershell

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.

like image 723
xHypnosia Avatar asked Jan 04 '19 09:01

xHypnosia


2 Answers

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
like image 162
Paweł Dyl Avatar answered Oct 04 '22 21:10

Paweł Dyl


Getting connection string from App.Config

$appConfigFile = [IO.Path]::Combine($currentDirectory, '.\MyFile.config')

initialize the xml object

$appConfig = New-Object XML

load the config file as an xml object

$appConfig.Load($appConfigFile)

iterate over the settings which you want

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>
like image 34
HariHaran Avatar answered Oct 04 '22 21:10

HariHaran