【问题标题】:Using CurrentDomain.SetData("APP_CONFIG_FILE") doesn't work in PowerShell ISE使用 CurrentDomain.SetData("APP_CONFIG_FILE") 在 PowerShell ISE 中不起作用
【发布时间】:2012-11-05 09:53:07
【问题描述】:

我正在尝试在 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 中执行它时,它没有按预期工作。

【问题讨论】:

    标签: .net-4.0 windows-8 powershell-3.0 powershell-ise


    【解决方案1】:

    这是因为 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
    

    【讨论】:

    • 这对我有用。我在使用常规 shell 和 ISE 时也遇到了同样的问题。
    • 也适合我。最后一行只是在正确修复 APP_CONFIG_FILE 后可以执行的操作的示例。
    • 不幸的是,这不适用于 PowerShell 7 和 Windows 10。复制并粘贴到 ps1 文件的确切示例脚本并从 $PathToConfig 指向 mycode.dll.config 的 Powershell 控制台运行文件仍然返回 LocalSqlServer 作为连接字符串,而不是我的配置文件中的连接字符串。 mycode.dll.config 文件有效并且在其他地方运行时被 dll 正确读取。 PowerShell 7 是否有可能打破了这一点?我会尝试找到更早的版本。
    【解决方案2】:

    起飞[0] 对我有用。

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

    【讨论】:

      猜你喜欢
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多