Skip to content

Commit 55c7a85

Browse files
author
James Brundage
committed
Search-PipeScript: Searching with the AST (Fixes #307)
1 parent 3afcdd1 commit 55c7a85

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

Search-PipeScript.ps1.ps1

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,15 @@ function Search-PipeScript
2020
[OutputType('Search.PipeScript.Result')]
2121
[Alias('Search-ScriptBlock')]
2222
param(
23-
# The ScriptBlock that will be searched.
23+
# The input to search.
24+
# This can be a `[string]`, `[ScriptBlock]`, `[IO.FileInfo]`, or `[Ast]`.
2425
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
2526
[Alias('ScriptBlock','Text')]
26-
[ValidateTypes(TypeName={[string], [scriptblock],[IO.FileInfo]})]
27+
[ValidateTypes(TypeName={[string], [scriptblock],[IO.FileInfo], [Management.Automation.Language.Ast]})]
2728
$InputObject,
2829

2930
# The AST Condition.
30-
# These Script Blocks
31+
# These conditions will apply when the input is a `[ScriptBlock]`, `[Ast]`, or PowerShell file.
3132
[Parameter(ValueFromPipelineByPropertyName)]
3233
[Alias('ASTDelegate')]
3334
[ScriptBlock[]]
@@ -80,23 +81,30 @@ function Search-PipeScript
8081
# Read the file contents as text.
8182
$text = [IO.File]::ReadAllText($inputCommand.Source)
8283
}
83-
}
84+
}
85+
86+
$ast = $null
8487

8588
# If the inputObject was a [ScriptBlock]
8689
if ($InputObject -is [scriptblock]) {
8790
$scriptBlock = $InputObject # set $ScriptBlock
88-
}
91+
$ast = $scriptBlock.Ast # and set $ast to the $ScriptBlock`s AST.
92+
# Reset $text to the ScriptBlock contents.
93+
$Text = "$scriptBlock"
94+
} elseif ($InputObject -is [Management.Automation.Language.Ast]) {
95+
# If the input was an [AST]
96+
# set the AST.
97+
$ast = $InputObject
98+
$text = $ast.Extent.ToString()
99+
}
89100

90101
# If the InputObject is a string
91102
if ($InputObject -is [string]) {
92103
$Text = $InputObject # set $Text.
93104
}
94105

95106
# If we have a ScriptBlock
96-
if ($scriptBlock) {
97-
# Reset $text to the ScriptBlock contents.
98-
$Text = "$scriptBlock"
99-
107+
if ($ast) {
100108
# If we have an ASTType to find
101109
if ($AstType) {
102110
foreach ($astTypeName in $AstType) {
@@ -151,7 +159,7 @@ function Search-PipeScript
151159
if ($AstCondition) {
152160
foreach ($condition in $AstCondition) {
153161
# Find all of the results.
154-
$ScriptBlock.Ast.FindAll($condition, ($Recurse -as [bool])) |
162+
$Ast.FindAll($condition, ($Recurse -as [bool])) |
155163
.InputObject = $inputObject .Result {
156164
$_
157165
} .Expression = $condition .ScriptBlock {

0 commit comments

Comments
 (0)