我最近在模塊清單中發現了 ScriptsToProcess 成員,并試圖探索使用它來簡化模塊中下標的組織。與其擁有一個單獨的模塊下標來加載我的所有下標,我認為重用我現有的清單檔案來加載 ScriptsToProcess 成員中的下標會更優雅。
它似乎對我的列舉有用——至少,我認為是這樣。雖然我的函式不起作用,但我還沒有讓模塊運行到足夠遠的地方,它試圖實體化它的一個類。
例子:
PS>New-Item -Path test/test.psm1 -Force
PS>cd test
測驗.psm1
Function testModule {
callEcho
}
Export-ModuleMember -Function testModule
測驗.psd1
PS>New-ModuleManifest -Path .\test.psd1 -RootModule .\test.psm1 -ScriptsToProcess .\subscripts\functions.ps1
PS>New-Item -Path subscripts/functions.ps1 -Force
函式.ps1
Function writeEcho {
write-host 'it worked!'
}
Write-Host 'ScriptsToProcess has loaded me'
PS>Import-Module .\test.psd1 -Force
PS>testModule
callEcho : The term 'callEcho' 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.
我的模塊無權訪問該功能。
我認為這是有意的,所以還有其他方法可以解決,還是我需要制作一個單獨的檔案,在模塊開始時點源我的所有下標?
此外,這種行為是否也適用于類?
PS5.1.14393
uj5u.com熱心網友回復:
ScriptsToProcess腳本在匯入器的范圍內是點源代碼,除非該范圍恰好是全域范圍,否則[1]您的模塊將看不到定義。
要在模塊的背景關系中點源幫助腳本,請將它們放在名為的子目錄中,例如scripts,然后將以下代碼放入RootModule .psm1檔案中:
Get-ChildItem $PSScriptRoot/scripts -Filter *.ps1 |
ForEach-Object { . $_.FullName }
請注意,除非您明確匯出這些腳本中定義的函式,否則它們將僅在模塊內可見。
至于進口商可以使用的制作enum和class定義:
在你的模塊中定義它們并讓匯入器通過using module而不是通過匯入模塊Import-Module。
如果您不在模塊內也使用它們,請僅使用ScriptsToProcess腳本使enums 和classes 對匯入器可用。
請注意,如果您嘗試將相同的腳本與模塊內部 的點源一起使用,那么您最終會得到s 和es在這兩種情況下并不相同——即使它們看起來是一樣的。ScriptsToProcess enumclass
[1] 也就是說,當您Import-Module 直接從互動式 Powershell 提示符運行時(或當您使用等效機制時) - 重要的是匯入器運行的范圍。這與您將模塊加載到的范圍無關,例如Import-Module -Global
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/418465.html
標籤:
