2012-06-26 33 views

回答

16

我的股票回答關於排除函數是使用動詞名詞命名我想要導出的函數,並使用首字母大寫的一切。

然後,Export-ModuleMember -function *-*照顧它。

+3

這個答案的簡單和常規基礎真的對我說話! –

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 
    } 
} 

這是我用來V2創建ISE Function Explorer的技術。但是,我沒有看到爲什麼這種方式不能在ISE之外使用純文本。儘管如此,您仍需要解決脫字符行細節問題。這只是一個如何實現你想要的例子。

現在,過濾什麼是不需要的,並將其傳遞給Export-ModuleMember

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

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

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工作或後來因爲AST解析器和$PSCommandPath版本中引入3

相關問題