首页 > 解决方案 > 封装 Powershell 函数

问题描述

我不知道如何执行以下任务。与 OOP 中的类成员一样,我们可以使用 private 修饰符隐藏实现。我的目标是创建一个基本的 powershell 函数,其中包含多个函数用于代码重用的逻辑,同时将该函数隐藏在全局访问之外。根据以下参考https://ss64.com/ps/syntax-scopes.html,以下范围可用 Global、Script 和 Private。我对函数的标记不会产生预期的结果。封装的函数应该如下所示工作。

function Invoke-VMDoSomething {
    Invoke-PrivateMiniFunc
}

function Invoke-VMDoSomethingElse {
    Invoke-PrivateMiniFunc
}

function Invoke-PrivateMiniFunc {
    ###BaseReuseable code
}

假设的命令提示符

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

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

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

我怎样才能实现这个约定,我是否需要将函数存储在 .psm1 文件而不是 ps1 文件中?甚至可能吗?

标签: functionpowershellscoping

解决方案


也许不完全是您所追求的,但您可以将功能隐藏在模块中。

在您的情况下,创建一个新文件并将其保存为 *.psm1 (我称之为演示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

最后一个命令Export-ModuleMember定义了您想要公开的功能以及不公开的功能。

接下来,在另一个文件中导入该模块。

在那里,只有导出的函数是可见/可调用的,但Invoke-PrivateMiniFunc不是:

Import-Module 'D:\InvokeModule.psm1'

Invoke-VMDoSomething      # works as expected

Invoke-VMDoSomethingElse  # works as expected

Invoke-PrivateMiniFunc    # errors out

结果:

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

推荐阅读