Skip to content

Instantly share code, notes, and snippets.

@koohq
Created November 3, 2017 08:27
Show Gist options
  • Save koohq/c0808ea64724ee5a6df35ad1b78bc84f to your computer and use it in GitHub Desktop.
Save koohq/c0808ea64724ee5a6df35ad1b78bc84f to your computer and use it in GitHub Desktop.
A helper script for access to App.config by PowerShell
<##
# Config.ps1
#
# (c) 2017 koohq. Licensed under CC0.
# https://creativecommons.org/publicdomain/zero/1.0/legalcode
#>
function Initialize-AppConfigFile
{
[CmdletBinding()]
[OutputType()]
param(
[Parameter(mandatory)]
[string]$Path
)
Add-Type -AssemblyName System.Configuration
[AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $Path)
[Configuration.ConfigurationManager].GetField("s_initState", "NonPublic, Static").SetValue($null, 0)
[Configuration.ConfigurationManager].GetField("s_configSystem", "NonPublic, Static").SetValue($null, $null)
([Configuration.ConfigurationManager].Assembly.GetTypes() | where FullName -EQ "System.Configuration.ClientConfigPaths")[0].GetField("s_current", "NonPublic, Static").SetValue($null, $null)
}
function Import-AppConfigFile
{
[CmdletBinding()]
[OutputType([PSCustomObject])]
param(
[Parameter(mandatory)]
[string]$Path
)
[xml]$config = Get-Content -Path $Path -Raw
$appSettings = New-Object System.Collections.Specialized.NameValueCollection
$config.SelectNodes("//appSettings/add") | foreach { $appSettings[$_.key] = $_.value }
$connectionStrings = New-Object System.Configuration.ConnectionStringSettingsCollection
$config.SelectNodes("//connectionStrings/add") | foreach {
$connectionStrings.Add((New-Object System.Configuration.ConnectionStringSettings @($_.name, $_.connectionString, $_.providerName)))
}
[PSCustomObject]@{
AppSettings = $appSettings
ConnectionStrings = $connectionStrings
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment