Dot-Net

Powershell 呼叫使用 App.config 的 .NET 程序集

  • May 7, 2009

我有一個 Powershell 腳本,它正在載入一個 .NET 程序集(在我的例子中是 .EXE)並呼叫一個使用 app.config 拉取加密連接字元串的公共方法。

該腳本將程序集的 exe.config 作為 powershell.exe.config 動態復製到 Powershell ($pshome) 文件夾,並且能夠從我的開發框執行得很好。問題是它不能從標準的 Windows Server 2003 安裝中執行。

我驗證了 exe.config 已正確複製到 powershell 目錄。我已經執行了 SysInternals Process Explorer 並驗證了該程序正在訪問配置文件(沒有文件未找到消息)。我遠端調試了 powershell.exe 實例,可以看到程序集載入正常,但無法訪問 ConfigurationManager.AppSettings[…] 值(返回 null)。

我沒主意了。我讀過我可能可以使用單獨的應用程序域,但我沒有看到使用 Powershell 執行此操作的範例。

我的程式碼起到以下作用:

$absolute_path = "c:\foo.exe"
$config_path = $absolute_path + ".config"
copy "$config_path" "$pshome\powershell.exe.config" -Force
[Reflection.Assembly]::LoadFrom($absolute_path)
$foo = new-object MyFooAssembly.FooClass
$foo.DoSomething()  

在 Vista 中程式碼有效,在 Windows Server 2003 中程式碼無效。

嘗試:

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

引用自:https://stackoverflow.com/questions/835862