My Technical Notes

Wednesday, 16 December 2015

PowerShell: Using App.Config within script

Use the following code:


Add-Type -AssemblyName System.Configuration
$appConfigPath = 'C:\path\to\App.config'
[AppDomain]::CurrentDomain.SetData('APP_CONFIG_FILE', $appConfigPath)

[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)

Additionally, there may be an `nlog` element within the app.config which we also want to load:


[NLog.LogManager]::Configuration = New-Object NLog.Config.XmlLoggingConfiguration @($appConfigPath)

References

No comments: