【发布时间】:2023-03-13 16:51:01
【问题描述】:
环境
我有以下文件夹结构,用于保存 powershell 模块:
C:
PsModules
...
util
util.psm1 (this contains implementation of 'Test-Function')
util.test.ps1
ftp
ftp.psm1
http.test.ps1
...
c:\PsModules 中大约有 50 个文件夹和模块。
我已将环境变量PSModulePath 设置为包含c:\PsModules。这似乎符合“格式良好的模块”described in Microsoft's documentation 和this answer 的条件。
症状
有时 Test-Function 在从 ISE 调用时不会自动找到。事实上,在任何给定的 ISE 新推出时,总会有一些(看似不可预测的)模块无法自动找到。例如,无法自动找到Test-Function,如下所示:
PS C:\> Test-Function
Test-Function : The term 'Test-Function' is not recognized as the name
of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is
correct and try again.
...
+ FullyQualifiedErrorId : CommandNotFoundException
乍一看,这似乎表明util.psm1 不是“格式正确的”。如果它不是“格式正确的”,那么 ListAvailable 应该不起作用。但它确实有效:
c:\> get-module -ListAvailable util
Directory: c:\PsModules\util
ModuleType Version Name ExportedCommands
---------- ------- ---- ----------------
Script 0.0 util
PS C:\> Test-Function
...
+ FullyQualifiedErrorId : CommandNotFoundException
另外,模块调用Get-Command后,模块中的命令就可以通用了:
c:\> Get-Command -Module util
CommandType Name ModuleName
----------- ---- ----------
Function Test-Function util
c:\> Test-Function
Call to Test-Function succeeded!
问题
自动发现和模块自动加载是否应该可靠且可预测?
如何解决为什么 powershell 有时在调用
Get-Command -module之前找不到命令?依靠 powershell 自动加载模块是不好的做法吗?如果是这样,自动加载模块的好习惯是什么?
【问题讨论】:
标签: powershell module autoloader