2016-10-07 17 views
4

私はPesterスクリプトを解析し、-Tagパラメータから値を抽出しようとしています。誰でもこれを行う方法を知っています[System.Management.Automation.PSParser]?私は[System.Management.Automation.PSParser]::Tokenize()から返されたトークンをループする必要があると思っていましたが、それはかなりkludgyと思われ、-Tagの値は非常に実用的ではない多くの異なる形式で与えられます。ASTを使用したPowerShellスクリプトの解析

私は、ブロック名が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パーサ使用

乾杯

答えて

4

$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でデバッガを使用して、さまざまなデータ型のケースを検査します。

+0

ありがとう@ w0xx0m。少し修正して、タグを[文字列]または[文字列[]]として引き出すことができました。 – devblackops

関連する問題