9

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.

NightShovel
  • 3,032
  • 1
  • 31
  • 35

2 Answers2

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
Community
  • 1
  • 1
Michael
  • 11,571
  • 4
  • 63
  • 61
  • This worked for me. I was also having the same problem using regular shell as well as ISE. – rikkit Feb 08 '16 at 12:01
  • Works for me as well. The last line is just an example of what you can do after you have properly fixed APP_CONFIG_FILE. – Jon Newman May 10 '19 at 16:27
  • Unfortunately this does not work for me with PowerShell 7 and Windows 10. The exact example script copied and pasted to a ps1 file and run from the Powershell console where $PathToConfig points to a mycode.dll.config file still returns LocalSqlServer as the connection string rather than the one in my config file. The mycode.dll.config file is valid and is read correctly by the dll when run elsewhere. Is it possible that PowerShell 7 has broken this? I'll try and find an earlier version. – Steven Palmer Jun 17 '20 at 08:41
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)

woot
  • 7,406
  • 2
  • 36
  • 55
icoxfog417
  • 137
  • 1
  • 4