【问题标题】:PowerShell : Is it mandatory to save script module in same name as directoryPowerShell:是否必须将脚本模块保存在与目录相同的名称中
【发布时间】:2020-07-19 14:21:00
【问题描述】:

关于模块,Doc 提到了它的可取性

使用 .psm1 扩展名保存 PowerShell 脚本。对脚本和保存脚本的目录使用相同的名称。

要安装和运行您的模块,请将模块保存到适当的 PowerShell 路径之一,然后使用 Import-Module。

PowerShell 路径 -> 位于$env:PSModulePath

我没有关注它们并将脚本模块chart_gui.psm1 保存在本地文件夹之一中,我仍然可以Import-Module 并在其中调用函数,但Remove-Module 抛出错误。

Import-Module 'H:\path_x\chart_gui.psm1'
#Call the function
$selectedCharts = selectCharts     
Remove-Module 'H:\path_x\chart_gui.psm1'

我的错误:

Remove-Module : No modules were removed. Verify that the specification of modules to remove is correct and those modules exist in the runspace.

我的$env:PSModulePath

PS C:\Users\xxx> $env:PSModulePath
C:\Users\xxx\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\Windo
wsPowerShell\v1.0\Modules

【问题讨论】:

    标签: powershell


    【解决方案1】:

    Remove-Module 并非旨在接受文件路径以识别要删除的模块。

    改为使用以下方法之一:

    # By simple name.
    # If your module is just a stand-alone *.psm1 file, the module name
    # is the base name of that file (the file name without extension).
    Remove-Module -Name chart_gui  # -Name is optional
    
    # Example of a fully qualified module name, which assumes a module 
    # that has a manifest file (*.psd1).
    # Again, the base name of that file is implicitly the module name, and,
    # typically, modules with *.psd1 files are placed in folders of the same
    # name.
    # Use the values specific to your module.
    # To eliminate all ambiguity, you can also add a 'Guid' key with the GUID
    # from your manifest.
    Remove-Module -FullyQualifiedName @{ ModuleName = 'chart_gui'; RequiredVersion = '1.0.0' }
    
    # By PSModuleInfo object, as reported by Get-Module or Import-Module -PassThru
    Get-Module -Name chart_gui | Remove-Module  # -Name is optional
    
    • 通常,只有 一个 具有给定名称的模块会在会话中加载,但可以并排加载多个。 这时候你需要 -FullyQualifiedName 参数(Get-ModuleRemove-Module 都支持)来消除歧义。

    • 避免歧义的一种简单方法是在调用Import-Module(带有显式路径)时使用-PassThru,它会输出描述模块的System.Management.Automation.PSModuleInfo 实例,您可以稍后将其传递给Remove-Module

    # Load (import) the module; -PassThru passes the
    # imported module through as a PSModuleInfo object, which you can later pass
    # to Remove-Module.
    $module = Import-Module -PassThru 'H:\path_x\chart_gui.psm1'
    
    # ... work with the module
    
    # Unload it again.
    $module | Remove-Module
    

    【讨论】:

      【解决方案2】:

      这可能仍然不是合适的方法,但我可以通过使用来避免错误

      Remove-Module 'chart_gui'
      

      【讨论】:

        猜你喜欢
        • 2020-10-20
        • 1970-01-01
        • 2012-10-26
        • 2016-06-26
        • 2018-09-23
        • 1970-01-01
        • 2019-03-24
        • 1970-01-01
        • 2020-10-11
        相关资源
        最近更新 更多