Powershell调用使用App.config的.NET程序集

Gab*_*beA 20 .net powershell app-config

我有一个Powershell脚本,它正在加载.NET程序集(在我的例子中是.EXE)并调用一个公共方法,该方法使用app.config来提取加密的连接字符串.

该脚本将程序集的exe.config动态复制到Powershell($ pshome)文件夹作为powershell.exe.config,并且能够从我的开发框运行就好了.问题是它不能从标准的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()  
Run Code Online (Sandbox Code Playgroud)

在Vista中代码可以工作,在Windows Server 2003中,代码不起作用.

Chr*_*ard 37

尝试:

[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $config_path)
Run Code Online (Sandbox Code Playgroud)


Gab*_*beA 5

经过进一步的研究,我找到了原因.在脚本的早期点,我正在加载SMO:

$null = [reflection.assembly]::loadwithpartialname("microsoft.sqlserver.smo") 
Run Code Online (Sandbox Code Playgroud)

我相信这有些如何破坏我的配置设置.解决方法就是克里斯首先提到这个电话:

[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $null)
$null = [reflection.assembly]::loadwithpartialname("microsoft.sqlserver.smo") 
Run Code Online (Sandbox Code Playgroud)

然后我第二次打电话到另一个组件做这个:

$config_path = $assembly_exe + ".config"
[System.AppDomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $config_path)
[Reflection.Assembly]::LoadFrom($assembly_exe)
Run Code Online (Sandbox Code Playgroud)

问题似乎已经解决了......