9

我正在尝试在 PowerShell ISE 中使用 .NET 4.0 程序集,并尝试更改通过以下方式使用的配置文件:

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

[Configuration.ConfigurationManager]::ConnectionStrings.Count 总是返回“1”,
而“[Configuration.ConfigurationManager]::ConnectionStrings[0].Name”总是返回“LocalSqlServer”,并且那个 ConnectionString 名称不在我的“.config”中文件。

请注意,从 PowerShell 命令提示符执行 PowerShell 脚本会按预期运行。只是当我从 PowerShell ISE 中执行它时,它没有按预期工作。

4

2 回答 2

24

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
于 2013-03-14T07:20:41.147 回答
2

起飞[0]对我有用。

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

于 2014-05-28T01:15:06.117 回答