Dot-Net-4.0
使用 CurrentDomain.SetData(‘APP_CONFIG_FILE’) 在 PowerShell ISE 中不起作用
我正在嘗試在 PowerShell ISE 中使用 .NET 4.0 程序集,並嘗試更改通過以下方式使用的配置文件:
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $PathToConfig);$$ Configuration.ConfigurationManager $$::ConnectionStrings.Count 始終返回“1”
和“$$ Configuration.ConfigurationManager $$::連接字元串$$ 0 $$.Name”始終返回“LocalSqlServer”,並且該 ConnectionString 名稱不在我的“.config”文件中。 請注意,從 PowerShell 命令提示符執行 PowerShell 腳本會按預期執行。只是當我從 PowerShell ISE 中執行它時,它沒有按預期工作。
這是因為 PowerShell ISE 的 app.config 路徑已經被載入和記憶體,所以之後更改 app.config 路徑不會有任何影響: stackoverflow.com/q/6150644/222748
這是一個範例腳本,它將清除記憶體的路徑,以便在 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