Euler
Euler

Reputation: 322

Encapsulating Powershell Functions

I am at a lost as to how to perform the following task. As with class members in OOP, we are allowed to hide away implementation with a private modifier. My goal is to create a base powershell function that contains logic that is used by several functions for code reuse while hiding away that function from global access. According to the following reference https://ss64.com/ps/syntax-scopes.html , the following scopes are available Global, Script, and Private. My labeling of the functions do not produce the desired result. The ecapsulated function should work as shown below.

function Invoke-VMDoSomething {
    Invoke-PrivateMiniFunc
}

function Invoke-VMDoSomethingElse {
    Invoke-PrivateMiniFunc
}

function Invoke-PrivateMiniFunc {
    ###BaseReuseable code
}

Hypothetical Command Prompt

PS > Invoke-VMDoSomething <<<Invoke-PrivateMiniFunc Executes successfully

PS > Invoke-VMDoSomethingElse <<<Invoke-PrivateMiniFunc Executes successfully 

PS > Invoke-PrivateMiniFunc <<<Fails Cannot find Such Commandlet -- Desired result.

How can I implement this convention and do I need to store the functions in a .psm1 file vice a ps1 file? Is it even possible?

Upvotes: 1

Views: 1258

Answers (1)

Theo
Theo

Reputation: 61123

Maybe not exactly what you are after, but you can hide functions inside a module.

In your case, create a new file and save it as *.psm1 (for demo I call it InvokeModule.psm1)

function Invoke-VMDoSomething {
    Invoke-PrivateMiniFunc
}

function Invoke-VMDoSomethingElse {
    Invoke-PrivateMiniFunc
}

function Invoke-PrivateMiniFunc {
    Write-Host "Called by: $((Get-PSCallStack)[1].FunctionName)" 
}

# export the functions you want to make available and leave out 
# the functions you want to keep hidden (but available to the functions in the module)

Export-ModuleMember -Function Invoke-VMDoSomething, Invoke-VMDoSomethingElse

The last command Export-ModuleMember defines what functions you want exposed en what not.

Next, in another file import that module.

In there, only the Exported functions are visible/callable but the Invoke-PrivateMiniFunc is not:

Import-Module 'D:\InvokeModule.psm1'

Invoke-VMDoSomething      # works as expected

Invoke-VMDoSomethingElse  # works as expected

Invoke-PrivateMiniFunc    # errors out

Result:

Called by: Invoke-VMDoSomething
Called by: Invoke-VMDoSomethingElse
Invoke-PrivateMiniFunc : The term 'Invoke-PrivateMiniFunc' 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:7 char:1
+ Invoke-PrivateMiniFunc
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Invoke-PrivateMiniFunc:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Upvotes: 2

Related Questions