Powershell 加载自定义程序集配置文件

Powershell load custom assembly config file

我有一个 DLL 文件,由我的 C# 代码在 visual studio 中创建。我需要从 powershell 运行 我的代码,因此我使用 Add-Type 方法加载我的程序集。

我的 Powershell 代码: Add-Type -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll [MyAssembly.MyClass]::MyStaticMethod()

当我将 return "Hello World" 放入 MyStaticMethod 时,一切正常。

当然,我的程序需要一些功能并且需要一个配置文件。 我将我的 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: An error occurred creating the configuration section handler for myCustomSection: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. (C:\Users\MyUserName\AppData\Local\Temp\tmp2EB6.tmp line 4) ---> System.IO.FileNotFoundException: Could not load file or assembly 'MyAssembly' or one of its dependencies. The system cannot find the file specified. at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)

它试图找到 'MyAssembly',正如我在配置文件中定义的那样。 MyAssembly.dll 是我创建的一个dll。但即使我的 powershell 中有这一行,它也不起作用: 添加类型 -Path C:\MyDirectoryWithDllFiles\MyAssembly.dll

有什么建议可以使它正常工作吗?

解法:

感谢 JayKul 在

的回答

我将它添加到配置部分,现在它工作正常: 版本=1.0.0.0,文化=中性,PublicKeyToken=null

<section name="myCustomSection" type="MyAssembly.MyCustomConfigurationSetting, MyAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />