PowerShell :是否必须将脚本模块保存在与目录相同的名称中



关于模块,Doc提到它更可取

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

若要安装和运行模块,请将模块保存到相应的 PowerShell 路径之一,然后使用导入模块。

PowerShell 路径 ->位于$env:PSModulePath

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

Import-Module 'H:path_xchart_gui.psm1'
#Call the function
$selectedCharts = selectCharts     
Remove-Module 'H:path_xchart_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:Usersxxx> $env:PSModulePath
C:UsersxxxDocumentsWindowsPowerShellModules;C:Program FilesWindowsPowerShellModules;C:Windowssystem32Windo
wsPowerShellv1.0Modules
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_xchart_gui.psm1'
# ... work with the module
# Unload it again.
$module | Remove-Module

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

Remove-Module 'chart_gui'

相关内容

最新更新