我可以从Export-ModuleMember中排除单个函数吗?

时间:2012-06-26 02:16:46

标签: powershell powershell-module

我在PowerShell脚本模块中定义了大量函数。我想使用Export-ModuleMember -Function *,但我想排除一个功能。排除这一功能比列出所有包含的功能更容易。反正有没有实现这个目标?

4 个答案:

答案 0 :(得分:16)

关于排除函数的我的股票答案是对我想要导出的函数使用动词 - 名词命名,并对其他所有函数使用初始大写。

然后,Export-ModuleMember -function *-*会处理它。

答案 1 :(得分:4)

查找脚本中的所有函数,然后根据要排除的内容进行过滤(假设PowerShell v2):

$errors = $null 
$functions = [system.management.automation.psparser]::Tokenize($psISE.CurrentFile.Editor.Text, [ref]$errors) `
    | ?{(($_.Content -Eq "Function") -or ($_.Content -eq "Filter")) -and $_.Type -eq "Keyword" } `
    | Select-Object @{"Name"="FunctionName"; "Expression"={
        $psISE.CurrentFile.Editor.Select($_.StartLine,$_.EndColumn+1,$_.StartLine,$psISE.CurrentFile.Editor.GetLineLength($_.StartLine))
        $psISE.CurrentFile.Editor.SelectedText
    }
}

这是我用于创建ISE Function Explorer的v2的技术。但是,我没有看到为什么这不适用于ISE之外的纯文本。您需要解决插入行详细信息。这只是如何实现你想要的一个例子。

现在,过滤不需要的内容并将其传递给Export-ModuleMember

$functions | ?{ $_.FunctionName -ne "your-excluded-function" }

如果您使用的是PowerShell v3,请parser makes it a lot easier

答案 2 :(得分:1)

所以我知道这很晚,但是简单的解决方案是在Export-ModuleMember cmdlet之后放置不需要导出的所有功能。在该语句之后定义的任何函数将不会导出,并且将对您的模块可用(也称为私有函数)。

也许更优雅的方法是包含一个模块定义文件,而根本不将该函数包含在要包含的函数列表中。

在模块内编写代码以在模块中不包含函数的想法似乎过于复杂,这不是一项新功能,自PowerShell诞生以来,我一直将函数放在Export之后。

答案 3 :(得分:0)

我的解决方案,使用PowerShell V3,ravikanth(在他的解决方案中使用V2)暗示,是定义PSParser模块:

Add-Type -Path "${env:ProgramFiles(x86)}\Reference Assemblies\Microsoft\WindowsPowerShell\3.0\System.Management.Automation.dll"

Function Get-PSFunctionNames([string]$Path) {
    $ast = [System.Management.Automation.Language.Parser]::ParseFile($Path, [ref]$null, [ref]$null)
    $functionDefAsts = $ast.FindAll({ $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)
    $functionDefAsts | ForEach-Object { $_.Name }
}

Export-ModuleMember -Function '*'

在模块中,如果我想要排除给定的函数,最后一行看起来像:

Export-ModuleMember -Function ( (Get-PSFunctionNames $PSCommandPath) | Where { $_ -ne 'MyPrivateFunction' } )

请注意,这仅适用于PowerShell V3或更高版本,因为版本3中引入了AST解析器和$PSCommandPath

相关问题