【问题标题】:Can I excplicitly call a function in an imported module like myModule.MyFunction() in Powershell?我可以在 Powershell 中的 myModule.MyFunction() 等导入模块中显式调用函数吗?
【发布时间】:2012-12-06 08:32:07
【问题描述】:

如果我已将 moduleFoo 导入到包含函数 Bar() 的脚本中。

我可以这样调用这个函数吗:

moduleFoo.Bar

而不是

Bar

以便阅读脚本的人可以理解这个 Bar 是从哪个模块调用的?

【问题讨论】:

    标签: .net powershell module


    【解决方案1】:

    你可以给你的函数命名,比如:

    moduleFoo.Bar # prefixing each function in your module with the module name + .
    

    但这不尊重函数或 cmdlet (verb-noum) 的标准 powershell 命名约定。

    您还可以创建在函数/cmdlet 前面加上 modulefoo. 的别名

    如果您只需要知道函数/cmdlet 所属的模块的名称,您可以使用:

    (gcm bar).Modulename
    

    【讨论】:

    • 这似乎对我不起作用,有什么解释吗? PS>(gcm df).ModuleName CoreSmac PS>CoreSmac.df CoreSmac.df : Le terme «CoreSmac.df» n'est pas reconnu comme nom d'applet de commande, fonction, fichier de script ou programme exécutable. Vérifiez l'orthographe du nom, ou si un chemin d'accès existe, vérifiez que le chemin d'accès est correct et réessayez. Au caractère Ligne:1 : 1 + CoreSmac.df + ~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (CoreSmac.df:String) [], CommandNotFo undException + FullyQualifiedErrorId : CommandNotFoundException
    • @Kayasax 有一个误会:(gcm bar).Modulename return cmdlet/function 来自的模块的名称。
    • 是的,我理解,正在运行 (gcm df).ModuleName -> PS 响应 CoreSmac。现在我调用 CoreSmac.df -> CommandNotFound ... @Christian
    • @Kayasax 抱歉.. 但我没有在回答中说在(gcm df).ModuleName 之后您可以将df cmdlet 称为CoreSmac.df。这是误解;)
    • 哇,在您的回复中,您告诉#prefix 模块中的每个函数,模块名称为 + 。 CoreSmac 是我的模块名称, df 是我的函数名称 所以 CoreSmac.df 应该工作不?顺便说一句,我不能用@Christian 开始我的评论,你知道为什么吗?
    【解决方案2】:

    如果您使用 -AsCustomObject 开关导入模块,您可以像 $moduleFoo.Bar 一样调用它:

    $moduleFoo = Import-Module moduleFoo -AsCustomObject
    $moduleFoo.Bar
    

    另一种选择是使用命令全名(模块\命令)来调用它:

    PS> moduleFoo\Bar 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 2021-09-22
      • 2018-07-26
      • 2022-01-15
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多