c# - PowerShell Types.ps1xml 导入模块时找不到类型

标签 c# powershell types module binary

我在导入包含 list 、二进制文件(根模块)和定义引用二进制文件中标识的类型的类型转换器或代码属性的类型文件的模块时遇到问题。

当我尝试导入模块时,我可以从详细输出中看到类型文件是在导入二进制模块的类之前加载的:

VERBOSE: Loading module from path '...\bin\Debug\Module\manifest.psd1'.
VERBOSE: Loading 'TypesToProcess' from path '...\bin\Debug\Module\Type.PS1XML'.

在加载根模块之前,出现以下错误:

Import-Module : The following error occurred while loading the extended type data file: , ...\bin\Debug\Module\Type.PS1XML(64) :
Error: Unable to find type [MyRootModule.MyItemConverter].
At line:1 char:128
+ ... odule\Manifest.psd1 | Import-Module -verbose ; $Debu ...
+                                            ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Import-Module], RuntimeException
    + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.ImportModuleCommand

问题是,如何在导入根模块后加载类型(无需将整个模块转换为通过调用 Import-ModuleUpdate-TypeData< 加载所有内容的脚本)/code> 模块目录中的每个项目)?或者我必须采取什么其他方法来解决此错误并同时导入模块和类型?

这是一个简单的例子。该模块(现场炮制仅作为示例)有以下几项:

模块\manifest.psd1

模块\root.dll

模块\type.ps1xml

这是root.dll的内容

namespace MyRootModule {
  public class MyTestItem {
    public string Name {get; set;}
    public int Id {get; set;}
  }
  public class MyItemConverter : PSTypeConverter {
    // code omitted for brevity
    // effectively creates a 'MyTestItem' with id '1' for string input 'one', and vice versa.
  }
}

这是manifest.psd1的相关内容

@{
RootModule = 'root.dll'
TypesToProcess = 'type.ps1xml'
}

这是type.ps1xml的内容

<?xml version="1.0" encoding="utf-8" ?>
<Types>
  <Type>
    <Name>MyRootModule.MyTestItem</Name>
    <TypeConverter>
      <TypeName>MyRootModule.MyItemConverter</TypeName>
    <TypeConverter>
  </Type>
</Types>

如果我先加载二进制模块,然后强制加载 list 或使用 update-typedata -PrependPath $pathToTypeFile,一切正常,我可以按照我的预期使用转换器能够(即 [MyRootModule.MyTestItem]1 返回 [MyRootModule.MyTestItem] 的新实例),这表明问题与转换器本身无关。

TLDR; powershell 模块在二进制文件之前加载类型文件,由于当时未找到二进制文件中定义的类型,因此导入失败。

最佳答案

花了我一些时间,但我会在这里标记答案,以防其他人遇到这个问题。模块 list 中有一个我已经忘记/从未关注过的成员,RequiredAssemblies。您可以将 dll 标记为必需的程序集以及根模块,以便在加载类型文件之前导入它。 (注意:它仍然需要列为根或嵌套模块才能导入 cmdlet。)

例如,将上面列出的 list 更新为以下内容可修复该问题:

@{
RootModule = 'root.dll'
TypesToProcess = 'type.ps1xml'
RequiredAssemblies = 'root.dll'
}

关于c# - PowerShell Types.ps1xml 导入模块时找不到类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64128475/

相关文章:

c# - ProcessStartInfo.WorkingDirectory 属性为空

c# - 检索datagrid中的可见项列表

powershell - 在继续之前使用 powershell 等待特定行出现

json - 使用 PowerShell 如何在具有注释的 json 文件中替换和保存值

powershell/sqlplus 错误 SP2-0042 : unknown command " ■@" - rest of line ignored

c# - 如何将嵌套的三元运算符转换为嵌套的 if-else 语句?

c# - RegularExpression 没有按预期工作 C#

C++ Void 非指针

c - 字符串文字是否在 C 的编译时自动转换为 char*?

scala - 为什么创建元组的显式语法只允许 AnyRefs 作为类型注释?