Using CurrentDomain.SetData(“APP_CONFIG_FILE”) doe

2019-02-07 02:04发布

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.

2条回答
Fickle 薄情
2楼-- · 2019-02-07 02:58

Taking off [0] works for me.

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

查看更多
男人必须洒脱
3楼-- · 2019-02-07 03:00

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
查看更多
登录 后发表回答