Using CurrentDomain.SetData(“APP_CONFIG_FILE”) doesn't work in PowerShell ISE

吃可爱长大的小学妹 提交于 2019-12-18 13:24:12

问题


I'm attempting to use a .NET 4.0 assembly in PowerShell ISE, and trying to change the config file which is used via:

[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $PathToConfig);    

[Configuration.ConfigurationManager]::ConnectionStrings.Count always returns "1",
and "[Configuration.ConfigurationManager]::ConnectionStrings[0].Name" always returns "LocalSqlServer", and that ConnectionString name is not in my ".config" file.

Note that executing the PowerShell script from a PowerShell command prompt functions as expected. It's just when I execute it from within PowerShell ISE, it doesn't work as expected.


回答1:


It's because the path to app.config for PowerShell ISE has already been loaded and cached so changing the app.config path afterwards won't make a difference: stackoverflow.com/q/6150644/222748

Here is an example script that will clear the cached path so it will work under PowerShell ISE:

[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $PathToConfig)
Add-Type -AssemblyName System.Configuration
[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)
[Configuration.ConfigurationManager]::ConnectionStrings[0].Name



回答2:


Taking off [0] works for me.

([Configuration.ConfigurationManager].Assembly.GetTypes() | where {$_.FullName -eq "System.Configuration.ClientConfigPaths"}).GetField("s_current", "NonPublic, Static").SetValue($null, $null)



来源:https://stackoverflow.com/questions/13420545/using-currentdomain-setdataapp-config-file-doesnt-work-in-powershell-ise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!