In PowerShell V2 we can use System.Management.Automation.PSParser
and do some
parsing ourselves using produced tokens:
function GetEndLineNumber {
param(
$scriptFile,
$functionName
)
$code = Get-Content -LiteralPath $scriptFile
$tokens = [System.Management.Automation.PSParser]::Tokenize($code, [ref]$null)
$waitForFuncName = $false
$funcFound = $false
$level = 0
foreach($t in $tokens) {
switch($t.Type) {
Keyword {
if ($t.Content -eq 'function') {
$waitForFuncName = $true
}
}
CommandArgument {
if ($waitForFuncName) {
$waitForFuncName = $false
$funcFound = $t.Content -eq $functionName
}
}
GroupStart {
++$level
}
GroupEnd {
--$level
if ($funcFound -and $level -eq 0 -and $t.Content -eq '}') {
return $t.StartLine
}
}
}
}
}
I did not test it thoroughly but I tried it for a few functions and scripts and it returned correct line numbers.