In this blog, we will look into loading and reading a config file, such as app.config (or) web.config, from current App Domain. PowerShell is an Object-Oriented programming language, with interactive command line shell for Windows. It is used to automate system tasks, such as batch processing, and create systems management tools for commonly implemented administrative tasks. We can load config files into current app domain and read it.
Let’s understand it with the below mentioned script in PowerShell ISE. When we start a new session in ISE, it loads PowerShell_ISE.exe.Config into current app domain and uses it as default configuration file.
We can load a custom config file into app domain using [appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $configpath), as shown below:
After loading c:\app.config, we are displaying path of currently loaded configuration file, using CurrentDomain.GetData() method.
Since, path of configuration file of PowerShell ISE is cached, changing its path will not clear cache and will still use old config file. We need to clear the cache, so that it can read the new config file after loading it. We use the following statements,
[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)
By following the above steps, we can load and read a custom config file in current app domain within PowerShell script.
I am ending the things here and hope this blog will be helpful for all.