使用AST解析PowerShell脚本

5
我正在尝试解析 Pester 脚本并从 -Tag 参数中提取值。有人知道如何使用 [System.Management.Automation.PSParser] 实现这一点吗?我曾经考虑过必须循环遍历从[System.Management.Automation.PSParser]::Tokenize() 返回的标记,但这似乎相当不可靠,因为-Tag 的值可以以许多不同的格式给出,所以并不实用。
最终,我希望返回一个集合,其中包含Describe块名称以及该块的标记列表(如果有)。
Name     Tags        
----     ----        
Section1 {tag1, tag2}
Section2 {foo, bar}  
Section3 {asdf}      
Section4 {}      

这里是我正在使用的样例 Pester 测试。

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
   }
}

有人对如何解决这个问题有什么想法吗?使用 [System.Management.Automation.PSParser] 是正确的方法还是有更好的方法?

谢谢

1个回答

6

使用 PS3.0+ 语言命名空间 AST 解析器:

$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中的调试器来检查各种数据类型。

感谢 @w0xx0m。稍作修改后,我能够将标签提取为 [string] 或 [string[]]。 - Brandon Olin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接