ParseInput 根据脚本中的注释更改 out Tokens

ParseInput changes the out Tokens based on the comments in the script

我想使用 Language.Parser class 中的 ParseInput 方法从脚本中获取所有标记。 问题是只要我在脚本中没有任何评论它就可以正常工作但是当我添加评论时停止进一步解析。实际上,它给了我整个评论以及评论之后的所有行作为最后一个标记。 如果您测试代码,您会看到 i 根据您在脚本中放置注释的位置而变化。 我使用了放在测试中的测试代码。ps1,用不同的代码测试仍然表现相同。

$ParsedScriptContent = [System.Management.Automation.Language.Parser]::ParseInput((Get-Content .\test.ps1), [ref]$ParserTokens, [ref]$null)

$i = 0

$ParserTokens | foreach{

    if($_){

        $i++
    }
}

Write-Host $i

使用:

System.Management.Automation.PSParser]::Tokenize((Get-Content C:\Script.ps1),[ref]$null) | %{$_}

为您的 Powershell Tokenize

如果您想使用 [System.Management.Automation.Language.Parser] 并从基于文件的脚本中提取,请将 ParseInput 更改为 解析文件

$ParsedScriptContent = [System.Management.Automation.Language.Parser]::ParseFile("C:\Test.ps1", [ref]$ParserTokens, [ref]$null)
$ParserTokens | ForEach-Object{$_}

如果使用 ParseInput 那么你应该像

$script=@'
$a = 1;$b = 2
#hello
$c = $a + $b;$c
'@
$ParserTokens = $null
$ParsedScriptContent = [System.Management.Automation.Language.Parser]::ParseInput($script, [ref]$ParserTokens, [ref]$null)
$ParserTokens | ForEach-Object{$_}