gpt4 book ai didi

powershell - 模块自动加载是否意味着可靠?

转载 作者:行者123 更新时间:2023-12-04 12:20:16 28 4
gpt4 key购买 nike

环境

我有以下文件夹结构,其中保存了 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 documentationthis 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 自动加载模块是不好的做法吗?如果是这样,自动加载模块的好习惯是什么?
  • 最佳答案

    我发现 FunctionsToExport模块 list 中的部分不能设置为 *

    这是不好的:

    # Functions to export from this module, for best performance, do not use 
    # wildcards and do not delete the entry, use an empty array if there are no
    # functions to export.
    FunctionsToExport = '*'

    这很好:
    # Functions to export from this module...
    FunctionsToExport = 'Test-Function, Test-Function2'

    关于powershell - 模块自动加载是否意味着可靠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661852/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com