Fellow PowerShell MVP Jeff Hicks posted a nice script to find all functions and filters in an ISE script and show the same in a GUI dialog. Jeff used Regex to figure out the function and filter details. This got me thinking. Why can’t we do the same using PowerShell ISE scripting object model?
UPDATE: As Jeff pointed out in the comments, this works only with PowerShell 3.0. There is no -Passthru switch in PowerShell 2.0 for Out-GridView cmdlet.
In fact, the answer is yes.
$ScriptBlock = {
$currentLine = $psISE.CurrentFile.Editor.CaretLine
$currentColumn = $psISE.CurrentFile.Editor.CaretColumn
$errors = $null
$functions = [system.management.automation.psparser]::Tokenize($psISE.CurrentFile.Editor.Text, [ref]$errors) | `
Where-Object {(($_.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
}},Content,StartLine, StartColumn
$psISE.CurrentFile.Editor.SetCaretPosition($currentLine,$currentColumn)
$selectedLine = $functions | Out-GridView -PassThru
if ($selectedLine) { $psISE.CurrentFile.Editor.SetCaretPosition($selectedLine.StartLine,$selectedLine.StartColumn) }
}
$psISE.CurrentPowerShellTab.AddOnsMenu.Submenus.Add("ISE Function _Explorer",$scriptBlock,"Alt+E")
In the above solution, I am using PowerShell tokenizer to find out the functions and filters.
[system.management.automation.psparser]::Tokenize($psISE.CurrentFile.Editor.Text, [ref]$errors) | `
Where-Object {(($_.Content -Eq "Function") -or ($_.Content -eq "Filter")) -and $_.Type -eq "Keyword" }
However, this won’t give us the names of the functions or filters. We need some additional work on that and I used the PowerShell ISE object model here. There is a small workaround. Instead of RegEx, I just select the text from each token given by the parser.
Select-Object @{"Name"="FunctionName"; "Expression"={
$psISE.CurrentFile.Editor.Select($_.StartLine, $_.EndColumn+1,$_.StartLine,$psISE.CurrentFile.Editor.GetLineLength($_.StartLine))
$psISE.CurrentFile.Editor.SelectedText
}},Content,StartLine, StartColumn
This is it. After this, I used Out-GridView to be able to select the function I need to go to.
Now, we can just select the function we need to go to and click OK.
This post is to just show how powerful ISE object model is and to demonstrate that — in PowerShell — there is always more than one way to do the same thing.






Pingback: PowerShell ISE Addon: ISE Function Explorer using the PowerShell 3.0 parser — Ravikanth Chaganti