【问题标题】:PowerShell 5 class: Import module needed for typePowerShell 5 类:类型所需的导入模块
【发布时间】:2018-02-15 14:07:43
【问题描述】:

我写了一个 PowerShell 5 类:

class ConnectionManager
{

  # Public Properties
  static [String] $SiteUrl
  static [System.Management.Automation.PSCredential] $Credentials
  static [SharePointPnP.PowerShell.Commands.Base.SPOnlineConnection] $Connection
  ...
}

类型“SharePointPnP.PowerShell.Commands.Base.SPOnlineConnection”来自自定义(已安装模块),名为“SharePointPnPPowerShell2016”

我的课程在另一个模块/文件中,名为“connection.manager.psm1”。

当我加载这个模块以使用这个类时,它返回了以下错误:

> Import-Module connection.manager.psm1
At connection.manager.psm1:6 char:11
+   static [SharePointPnP.PowerShell.Commands.Base.SPOnlineConnection]  ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type
[SharePointPnP.PowerShell.Commands.Base.SPOnlineConnection].

当我在加载我的模块之前在 PowerShell 会话中手动加载 (PNP) 模块时,它已正确加载并且我可以使用它。

但我不想总是在使用我的模块之前必须先手动加载另一个模块。我尝试通过添加将 PNP-Module 直接导入到我的模块中:

Import-Module "SharePointPnPPowerShell2016"

一开始,在类声明之前,但没有任何改变,仍然出现“无法找到类型”的错误。

任何想法如何正确地做到这一点?

【问题讨论】:

    标签: powershell class powershell-5.0 powershell-module import-module


    【解决方案1】:

    我认为您可以使用module manifest 解决此问题

    您可以使用“必需的模块”和“必需的程序集”部分。当您加载包含该类的自定义模块时,这应该处理加载需求(只要它们已安装)。

    【讨论】:

    • 你是对的。我通过使用包含以下行的模块清单成功对其进行了测试:RequiredModules = @('SharePointPnPPowerShell2016') 这导致模块被正确加载而没有错误。唯一的问题是,我有时需要版本 ...2016,有时需要 2013,并且不想要 2 个代码库。但这是我自己会解决的另一个问题:-)
    • 很高兴我能帮上忙!该名称是否适用于 SharePoiuntPnPPowerShell201* 等通配符?
    【解决方案2】:

    如果你在一个模块中声明了一个类,如果你Import-Module,你就不能使用它;只引入 cmdlet、函数和别名。相反,您的脚本应该Using module 模块;这将引入类以及其他导出的项目。

    (我实际上误读了问题;这不能解决询问者的具体问题——但是对于不使用其他模块中的类的类,这将允许从模块中导入类。询问者发现了一个已知问题在 PowerShell 中;有关更多信息,请参阅 cmets。)

    【讨论】:

    • 它看起来目前不在 PowerShell 5 中,但可能与 PowerShell 6.1 一起提供 - github.com/PowerShell/PowerShell/issues/2074 还是我错了?
    • 在您的模块中尝试Using module "SharePointPnPPowerShell2015"
    • 不幸的是,这似乎不起作用。我将“使用模块“SharePointPnPPowerShell2016”作为第一行”(并且此模块存在),但是当我在 powershell (5.0.10586.117)中使用“使用模块”加载我的模块时,它再次显示“无法找到类型 [SharePointPnP.PowerShell .Commands.Base.SPOnlineConnection]。"
    • 好的,这很可能是您从 GitHub 关注的问题。
    • 这不行,我过去也遇到过这个问题(和 Github 上的问题)。使用“调用者”脚本,您首先添加类型(通过 Add-Type 或使用反射),然后调用包含您的类的 PS 脚本应该可以工作......
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 2019-04-12
    • 2019-03-02
    • 2011-08-03
    • 2017-12-07
    相关资源
    最近更新 更多