簡體   English   中英

在模塊/ Powershell中調用函數

[英]Calling a function within module / Powershell

我必須遺漏一些基本的東西,但我是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

我打算在一個模塊中有多個功能,但這就是我所處的位置。

提前致謝

[編輯]我沒有使用-Force選項進行導入模塊。 下面的答案是不正確的,但也許Get-Command強制刷新? 無論哪種方式,我都會離開它以獲得完整的體驗!

感謝latkin將我推到另一條道路,我發現了這個:

如何從模塊中檢索命令

你不僅需要導入一個模塊,還必須“獲取”它(?)

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

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

感謝latkin快速響應!

我遇到了同樣的問題。 重現步驟:

  • 使用Import-Module語句編寫PowerShell腳本
  • 在PowerShell提示符下執行腳本
  • 向導入的模塊添加功能
  • 修改腳本以調用新添加的函數
  • 在同一PowerShell會話中再次執行腳本

-Force參數添加到Import-Module后,錯誤消失了。 一旦能夠調用導入模塊中的函數,就可以刪除-Force參數。

請注意, 拉特金在對該問題的評論中提到了這個解決方案。 我希望這會讓它更加明顯。

如果沒有從模塊中正確導出方法,則只需要Get-Command

在你的模塊的最后把這個:

Export-ModuleMember -Function UserSelectionList

請注意,它也接受通配符,例如,如果你有5個不同的Get-Some-Value函數遵循命名約定,你可以做

Export-ModuleMember -Function Get-*

關於-Force附注:所有這一切都是檢查模塊是否已經加載,如果是,則在繼續導入之前將其刪除。 這跟說:

Remove-Module userselectionlist.psm1
Import-Module userselectionlist.psm1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM