【问题标题】:How can I suppress "Unapproved verbs" in Powershell classes如何在 Powershell 类中抑制“未经批准的动词”
【发布时间】:2022-03-16 02:45:08
【问题描述】:

为了在 powershell (V7) 脚本中使用类,似乎有必要通过以下方式声明实现类(Powershell 语言)的模块

using module .\MyModule.psm1

模块“MyModule.psm1”通过导入一个powershell模块

Import-Module powershell-yaml -DisableNameChecking

如何在脚本执行期间抑制“未批准的动词”警告? DisableNameChecking 选项在这里似乎没有帮助

模块的完整示例

 Import-Module powershell-yaml -DisableNameChecking

 class TestManager { 
 hidden [string] $NodeTypeApplication = "Application"

 TestManager () {
 }

 [void] StartDeployment()
 {
     Write-Host("starting deployment...")

 }

}

【问题讨论】:

  • 我无法重现此问题,请提供显示此问题的示例 psm1 文件的内容
  • 是的,这不是我的类,似乎模块内的模块导入,包含类,触发了消息。已更新我的问题。
  • 那个 msg 是 PoSh 自己产生的还是 PSReadline 产生的?如果是第二个,那么您可以定义一个自定义规则以不显示该消息。
  • 由shell产生

标签: powershell


【解决方案1】:

虽然您确实使用 -DisableNameChecking 来导入 嵌套 模块 (powershell-yaml),但如果使用非标准功能,封闭 模块的警告可能会重新出现从一个嵌套模块成为封闭模块导出的一部分。

你有两个选择:

  • 如果您确实需要从封闭模块中导出(嵌套)非标准函数

    • 消除封闭模块警告的唯一方法也是使用
      Import-Module -DisableNameChecking 导入it,而不是通过using module

    • 警告:不幸的是,这排除了使用模块中定义的 PowerShell 自定义类;从 v7.0 开始,自定义类只有在您使用 using module 时才会对导入器可见(有关背景信息,请参阅 GitHub issue #2449)。

    • 解决这个问题:

      • 为您需要导出的那些非标准函数定义 包装器 函数,并为其指定符合标准的名称。
      • 然后从模块的导出中排除非标准函数 - 请参阅下一点。
  • 否则,从导出中排除非标准函数,您可以在 以下方式之一:

    • 如果您在封闭模块本身中实际上不需要它们,请通过仅将您确实需要的函数的名称传递给Import-Module-Function 参数来将它们从导入中排除。

    • 否则,您可以明确控制封闭模块导出的内容:

      • 您可以在封闭模块中使用Export-ModuleMember 调用。
      • 另外/另外,如果您使封闭模块使用module manifest*.psd1 文件),您可以限制导出哪些函数。

下面是原始问题的简单演示:

# Create a temp. nested module with a nonstandard function.
'function UnapprovedVerb-Foo { ''unapproved foo'' }' > tmp_nested.psm1

# Create the enclosing module that imports the nested module
# with warnings suppressed.
# However, because the enclosing module has no manifest, the nested
# functions are exported alongside its own functions.
'Import-Module $PSScriptRoot/tmp_nested.psm1 -DisableNameChecking; function Get-Foo { ''foo'' }' > tmp_enclosing.psm1

# This now triggers the warning - as import via `using module` would.
# Adding -DisableNameChecking would silence it, but `using module` has
# no equivalent mechanism - and you need the latter to import *custom PS classes*.
Import-Module ./tmp_enclosing.psm1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-11
    • 2014-12-16
    • 1970-01-01
    • 2021-06-17
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多