3

我必须在这里遗漏一些基本的东西,但我是powershell的新手......

我编写了一个函数并将其保存在一个名为“UserSelectionList.psm1”的文件中,该函数的存根如下:

function Global:UserSelectionList([String[]] $UserOptions)
{
...
}

然后我尝试用这个脚本调用它:

Import-module "l:\support downstream\solarc\cngl\powershell scripts\userselectionlist.psm1"
$Options = "a","b","c"
cls
$result = UserSelectionList $Options
echo $result

产生的错误是:

The term 'UserSelectionList' 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.
At line:5 char:28
+ $result = UserSelectionList <<<<  $Options
    + CategoryInfo          : ObjectNotFound: (UserSelectionList:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

我计划在一个模块中拥有多个功能,但这就是我所在的地方。

提前致谢

4

3 回答 3

7

我遇到了同样的问题。重现步骤:

  • 编写带有Import-Module语句的 PowerShell 脚本
  • 在 PowerShell 提示符处执行脚本
  • 向导入的模块添加函数
  • 修改脚本调用新增功能
  • Execute the script again, in the same PowerShell session

The error went away after I added the -Force argument to Import-Module. The -Force argument can be removed once the function in the imported module is able to be called.

Note that latkin has alluded to this solution in his comment to the question. I'm hoping this will make it more visible.

于 2016-10-18T09:30:13.100 回答
3

Get-Command仅当您没有从模块中正确导出方法时才需要。

在你的模块的最后放这个:

Export-ModuleMember -Function UserSelectionList

请注意,它也接受通配符,例如,如果您有 5 个不同的 Get-Some-Value 函数遵循命名约定,您可以这样做

Export-ModuleMember -Function Get-*

旁注-Force:所做的只是检查模块是否已加载,如果已加载,则在继续导入之前将其删除。这和说的一样:

Remove-Module userselectionlist.psm1
Import-Module userselectionlist.psm1
于 2015-11-07T17:37:46.847 回答
2

[编辑] 我没有使用 -Force 选项进行导入模块。下面的答案不正确,但也许 Get-Command 强制刷新?无论哪种方式,为了体验的完整性,我都会离开它!

感谢 latkin 将我推向另一条我发现这一点的路径:

如何从模块中检索命令

您不仅必须导入模块,还必须“获取”它(?)

Import-Module -Name <ModuleName> 
Get-Command -Module <ModuleName>

在我发出 Get-Command 后,一切都开始工作了!

感谢 latkin 的快速回复!

于 2012-11-27T19:46:33.107 回答