Thursday, November 28, 2013

How to load config file in PowerShell?

I had a problem with a customer where we would like to reuse one WCF endpoint from our web.config file. What Microsoft describes and a lot of blogs on the net, all you have to do is call [AppDomain]::CurrentDomain.SetData ("APP_CONFIG_FILE", $pathToConfig) http://msdn.microsoft.com/en-us/library/37z40s1c(v=vs.110).aspx. But it does not work because PowerShell already has loaded a config file loaded. Therefore, you should reset the config file “context” through reflection. To do so:

1 $pathToConfig = "C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config"
2 #Set the path to the new config file
3 [AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $pathToConfig)
4 [System.Configuration.ConfigurationManager].GetField("s_initState", [Reflection.BindingFlags] "NonPublic,Static").SetValue($null, 0)