问题
powershell modules make it possible to have private "methods", but I cant find any conventions or support for defining them as such. For larger scripts this is more than just a superficial code prettiness thing, it becomes very important to be able to tell if a method is local or not just by its name.
This sort of works but powershell complains every time I import that its not using a properly named verb. Is there a supported prefix for defining local functions/methods?
function _Get-Something {...}
function Get-SomethingElse { _Get-Something -arg sdfsdf .....}
Export-ModuleMember -Function Get-SomethingElse
回答1:
Using your example, I do not get the warning message (PowerShell 5.1) because you are not exporting the function _Get-Something
.
If I do export it (Export-ModuleMember -Function Get-SomethingElse, _Get-Something
), then the warning happens.
I'm not aware of any convention for this, but what I usually do is naming such a helper function within the module without a dash (_Get-Something
--> _GetSomething
) and use correct names with approved verbs for functions I do want to export. Then export the lazy way:
Export-ModuleMember -Function *-*
It is also possible to 'hide' helper functions inside the exported function that uses it, like
function Get-SomethingElse {
# helper function inside
function _Get-Something { Write-Host "Hi from $($MyInvocation.MyCommand)" }
_Get-Something -arg 'sdfsdf .....'
}
Export-ModuleMember -Function Get-SomethingElse
This too does not show the warning on my machine.
Lastly, you can get rid of the warning by adding the -DisableNameChecking
switch to the command:
Import-Module 'D:\test.psm1' -DisableNameChecking
Hope this helps
来源:https://stackoverflow.com/questions/60476716/conventions-and-native-support-for-defining-private-functions-inside-a-module