我有一个DLL文件,是从我的C#代码在Visual Studio中创建的。我需要从PowerShell来运行我的代码,因此我使用Add-Type方法来加载程序集。
我的PowerShell代码如下:
Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll
[MyAssembly.MyClass]::MyStaticMethod()
当我在MyStaticMethod中输入返回“Hello World”,一切正常。
当然,我的程序需要一些功能,需要使用配置文件。 我将我的PowerShell代码更新为以下内容:
[appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", "C:\MyDirectoryWithDllFiles\MyAssembly.dll.config")
Add-Type -AssemblyName System.Configuration
Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll
[MyAssembly.MyClass]::MyStaticMethod()
以下是配置文件的内容:(MyAssembly.dll.config)
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="myCustomSection" type="MyAssembly.MyCustomConfigurationSetting, MyAssembly" />
</configSections>
<!--this is the custom config section for myCustomSection-->
<myCustomSection>
<!-- some items -->
</myCustomSection>
</configuration>
在 MyStaticMethod 方法中,我从配置文件中获取条目,在从 Visual Studio 运行代码时可以正常工作。但当我运行 PowerShell 代码时,如上所述,会出现以下错误:
PS C:\MyDirectoryWithDllFiles> [MyAssembly.MyClass]::MyStaticMethod() Errors: [System.Configuration.ConfigurationErrorsException: 在创建 myCustomSection 配置节处理程序时出现错误: 无法加载文件或程序集 'MyAssembly' 或它的某一个依赖项。系统找不到指定的文件。(C:\Users\MyUserName\AppData\Local\Temp\tmp2EB6.tmp 第 4 行) ---> System.IO.FileNotFoundException: 无法加载文件或程序集 'MyAssembly' 或它的某一个依赖项。系统找不到指定的文件。在 System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)
它试图查找“MyAssembly”,就像我在配置文件中定义的那样。MyAssembly.dll 是我创建的一个 DLL 文件。但是,即使我在 PowerShell 中有这一行也不起作用: Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll
有什么建议可以让这个工作起来吗?