【问题标题】:PowerShell Class Inheritance from separate file using Import-Module使用 Import-Module 从单独文件继承 PowerShell 类
【发布时间】:2017-08-23 20:20:18
【问题描述】:

我在这里做错了什么 - 还是 PowerShell v5 不支持单独的类文件和继承?

foo.ps1:

class foo
{
   [STRING] $test = 'Hello World';

   [STRING] PrintTest()
   {
      return $this.test;
   }
}

bar.ps1:

Import-Module "$PSScriptRoot\foo.ps1"

class bar : foo
{ }

控制台

PS C:\Script> Import-Module ./bar.ps1;

PS C:\Script> $myBar = New-Object bar;

PS C:\Script> $myBar.PrintTest();

Method invocation failed because [bar] does not contain a method named 'PrintTest'.

如果将 foo 和 bar 类放在同一个文件中,它就可以正常工作。但是我正在构建的类相当大,我想将它们分开。

【问题讨论】:

  • 你确定错误,你得到了什么?如果您从干净的 PowerShell 会话中执行此操作,我希望 ParseErrorImport-Module ./bar.ps1 上。
  • 是的,它加载 bar.ps1 没有错误。甚至可以毫无问题地创建 bar 对象。
  • 类不与模块一起导出。请参阅下面的答案。

标签: class powershell inheritance


【解决方案1】:

首先,模块文件的扩展名应为.psm1,因此您需要更改它。如果你不这样命名它们,我在下面引用的Using 语句将显示错误。

bar.psm1 应该包含对模块的引用,因为modules do not import classes

bar.psm1:

Using module ".\foo.psm1"

class bar : foo
{ }

但是,一旦你这样做了,bar 类就不会被导出,所以你必须编写一个单独的 ps1 文件,在顶部 Using module ".\bar.psm1" 中声明,然后在该脚本文件中你可以调用 [bar] 类。

【讨论】:

  • 成功了!谢谢你。我知道我错过了一些简单的东西。
猜你喜欢
  • 2014-06-21
  • 2021-03-15
  • 2018-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多