serving the solutions day and night

Pages

Thursday, November 9, 2017

PowerShell - Read App.config

## get current directory
$current_directory =  $(Get-Item ($MyInvocation.MyCommand.Path)).DirectoryName

## $MyInvocation.MyCommand.Path won't work if you call inside the function.
## so use ScriptName to get currect directory
$current_directory =  $(Get-Item ($MyInvocation.ScriptName)).DirectoryName

## path of config file
$app_config_path = $current_directory + "\App.config"

## reading configuration file
$xml_doc = [Xml](Get-Content $app_config_path)

## get appsettings value
$app_nodes = $xml_doc.configuration.appSettings.add
$url = ($app_nodes | where {$_.key -eq 'Url'}).value
$username = ($app_nodes | where {$_.key -eq 'UserName'}).value
$password = ($app_nodes | where {$_.key -eq 'Password'}).value

## get dbconnection setting
$con_nodes = $xml_doc.configuration.connectionStrings.add
$db_con = ($con_nodes | where {$_.name -eq 'DBConnectionString'}).connectionString

## display value
Write-Host  $url
Write-Host  $username
Write-Host  $password
Write-Host  $db_con

<#
App.config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Url" value="https://dns.com/Services/2017/Organization.svc" />
    <add key="UserName" value="mak@dns.com"/>
    <add key="Password" value="ABC123456!@#"/>
  </appSettings>
  <connectionStrings>
    <add name="DBConnectionString" connectionString="Data Source=MAK12345.dns.com,1044;Initial Catalog=COS_SVC;User ID=root; Password=DEF456$%^;" providerName="System.Data.SqlClient"/>
  </connectionStrings>
</configuration>
#>

No comments: