我需要从多功能脚本中获取函数的名称。这是我想出的。基于此,也许有人可以提供更短的版本。
# Get text lines from file that contain 'function'
$functionList = Select-String -Path $scriptName -Pattern "function"
# Iterate through all of the returned lines
foreach ($functionDef in $functionList)
{
# Get index into string where function definition is and skip the space
$funcIndex = ([string]$functionDef).LastIndexOf(" ") + 1
# Get the function name from the end of the string
$FunctionExport = ([string]$functionDef).Substring($funcIndex)
Write-Output $FunctionExport
}
我想出了一个较短的版本找到并列出在脚本列表的功能。这并不完美,并且会有问题,因为该模式只是“功能”一词,并且如果此方法假定它在任何地方找到了找到该关键字的功能。
要遍历文件并获取列表,我使用'Get-ChildItem'函数并使用递归选项传递路径和文件筛选器规范。
通过管道传递给'Select-String'并查找'Function'关键字。它不区分大小写,并会接受“功能”或“功能”。如果需要添加“-CaseSensitive”,则有一个区分大小写的选项。
然后迭代输出以获取实际的函数名称。 “Line”成员是一个字符串类型,我使用从第9位开始的“Substring”选项,它是刚刚通过“函数”标识符的长度。
$scriptPath = "c:\\Project"
$scriptFilter = "*.ps1"
(Get-ChildItem -Path $scriptPath -Filter $scriptFilter -Recurse | Select-String -Pattern "function") | %{ $_.Line.Substring(9) }
如果你的'.ps1'是'.psm1'相反,它会是一个模块,并获得函数列表会那么容易,因为'(导入模块C:\ someScript.psm1 -passThru ).ExportedFunctions.Values'。 (根据Martin的回答,用'&$ _。ScriptBlock'调用。) –