powershell - 使用 AST 解析 PowerShell 脚本

标签 powershell parsing abstract-syntax-tree

我正在尝试解析 Pester 脚本并从 -Tag 中提取值范围。任何人都知道如何使用 [System.Management.Automation.PSParser] 来做到这一点?.我在想我必须遍历从 [System.Management.Automation.PSParser]::Tokenize() 返回的 token 但这似乎很笨拙,而且考虑到 -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]正确的方法还是有更好的方法?

干杯

最佳答案

使用 PS3.0+ Language namespace 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 中的调试器检查各种数据类型情况。

关于powershell - 使用 AST 解析 PowerShell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39909021/

相关文章:

powershell - PowerShell Core无法识别unicode

javascript - 重写公式字符串以用 Math.pow(a, b) 替换 a^b

Java - 抽象语法树

c++ - 如何区分 Clang AST 访问者中的函数定义和函数声明

functional-programming - OCaml 访问者模式

python - 忽略具有某些文件类型的文件夹

regex - 在csv doc中使用powershell,需要迭代并插入字符

windows - Powershell 确定远程计算机操作系统

javascript - jquery 中的 JSON.parse 错误

c# - 提高字符串解析性能