c# - PowerShell 和服务器管理器模块的跨平台系统库引用

标签 c# powershell visual-studio-2012 .net-assembly

我正在编写的程序使用 System.Management.Automation 库来利用在那里定义的 PowerShell 类和接口(interface)。这些库有两个版本:1.0.0.0 和 3.0.0.0。 Windows Server 2008 在其 GAC 版本 1.0 中,Windows Server 2012 在其 GAC 中同时具有 1.0 和 3.0。

为了能够在VS项目中使用这个库,我不得不引用它。现在要做决定,我应该引用哪一个?好吧,因为两台服务器的 GAC 中都有 1.0,所以引用 1.0 应该是安全的。尽管如此,以防万一,如果 GAC 中存在一些罕见(或常见?)的情况,我会将其复制到本地。

使用这个库的示例代码:

using (PowerShell PS = PowerShell.Create())
{

    PS.AddScript("Import-Module ServerManager")
        .Invoke();
}

Import-Module Servermanager 命令导致 PowerShell 导入另一个 dll,Microsoft.Windows.ServerManager。问题从这里开始。

Windows Server 2008 只有此库的 6.1.0.0 版,而 Windows Server 2012 有 6.3.0.0 版。我假设 Automation 的 1.0 到 6.1 和 3.0 到 6.3 版本相似性并非巧合。

当我在 Windows Server 2008 上使用我的程序时,它工作正常,但是当我试图在 Windows Server 2012 上使用它时,这个 Automation 1.0 程序集正在尝试加载 ServerManager 程序集版本 6.1 (!),而 2012 没有没有。 2012 更喜欢使用 Automation assembly v3.0 并加载 ServerManager v6.3。

我假设有一些方法可以“告诉”程序在服务器版本 Y 时加载程序集 X,在服务器版本 B 时加载程序集 A,但它去哪里了?那么我怎么能确定我不会遇到一些有 2.0 或 4.0 版或其他版本的服务器。

问题是我无法引用(在本地复制)ServerManager 程序集,因为(我认为)只要我能“告诉”我的 程序应该在哪里寻找程序集,我就可以' 告诉自动化程序集到哪里寻找其他程序集。通过使用 procmon 进行分析,我可以看出它完全知道要查找的位置,因为它立即导航到 C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ServerManager 以查找 ServerManager 程序集.

我知道的可能的解决方案是:

  1. 我可以尝试使用 Assembly.Load()dynamic 对象在 visual studio 中动态加载程序集而不引用它们,作为某人建议,我应该在火热的 hell 中燃烧(我假设那个人提到它非常容易出错)。

  2. 我可以将我需要的程序集添加到 GAC,但这可能会导致一些依赖 hell ,因为 Automation 和 ServerManager 可能有很多其他依赖关系,而我现在才发现其中两个。

我还有哪些其他选择?

最佳答案

您是否尝试过在您的 .config 文件中为这些引用进行程序集重定向?

  <runtime>
    <assemblyBinding appliesTo="v2.0.50727" xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

关于c# - PowerShell 和服务器管理器模块的跨平台系统库引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32959609/

相关文章:

arrays - PowerShell 数组字典?

c++ - 未定义 'not' 命令 Visual Studio C++

c++ - 错误 LNK2019 : unresolved external symbol

c# - 仅针对发布版本从项目文件中删除注释

c# - 从数据库更新 Entity Framework 模型,无法识别自定义属性

c# - FileUpload - 验证是否上传了实际文件

c# - P/调用 vkGetPhysicalDeviceFeatures 访问冲突

azure - 2021 年,导出 Azure 自动化 AzureRunAsConnection 用于本地调试的证书的最快/最简单的方法是什么?

powershell - 导入表数据并使用databricks将其另存为json文档在adls gen2中

wpf - 仅在非常特殊的情况下,Visual Studio Intellisense不能在XAML上运行