Parsing PowerShell script with AST

I am trying to parse a Pester script and extract values ​​from a parameter -Tag. Does anyone know how to do this using [System.Management.Automation.PSParser]? I thought I would have to scroll through the tokens returned from [System.Management.Automation.PSParser]::Tokenize(), but this seems pretty kludgy and given that the values ​​for -Tagcan be provided in many different formats, and not very practical.

At the end of the day, I hope to return a collection with the name of the block Describeand a list of tags (if any) for this block.

Name     Tags        
----     ----        
Section1 {tag1, tag2}
Section2 {foo, bar}  
Section3 {asdf}      
Section4 {}      

Here is an example of the Pester tests I am working with.

describe 'Section1' -Tag @('tag1', 'tag2') {
    it 'blah1' {
        $true | should be $true
    }
}
describe 'Section2' -Tag 'foo', 'bar' {
    it 'blah2' {
        $true | should be $true
    }    
}
describe 'Section3' -Tag 'asdf'{
    it 'blah3' {
        $true | should be $true
    }
}
describe 'Section4' {
   it 'blah4' {
        $true | should be $true
   }
}

Anyone have any ideas on how to solve this? Is the [System.Management.Automation.PSParser]right way or is there a better way?

Greetings

+4
1

PS3.0 + :

$text = Get-Content 'pester-script.ps1' -Raw # text is a multiline string, not an array!

$tokens = $null
$errors = $null
[Management.Automation.Language.Parser]::ParseInput($text, [ref]$tokens, [ref]$errors).
    FindAll([Func[Management.Automation.Language.Ast,bool]]{
        param ($ast)
        $ast.CommandElements -and
        $ast.CommandElements[0].Value -eq 'describe'
    }, $true) |
    ForEach {
        $CE = $_.CommandElements
        $secondString = ($CE | Where { $_.StaticType.name -eq 'string' })[1]
        $tagIdx = $CE.IndexOf(($CE | Where ParameterName -eq 'Tag')) + 1
        $tags = if ($tagIdx -and $tagIdx -lt $CE.Count) {
            $CE[$tagIdx].Extent
        }
        New-Object PSCustomObject -Property @{
            Name = $secondString
            Tags = $tags
        }
    }
Name       Tags             
----       ----             
'Section1' @('tag1', 'tag2')
'Section2' 'foo', 'bar'     
'Section3' 'asdf'           
'Section4' 

, extent.
PowerShell ISE/Visual Studio/VSCode .

+4

Source: https://habr.com/ru/post/1657015/


All Articles