本文介绍了我如何选择“捕获"?在PowerShell中使用正则表达式的代码块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试分析许多目录中的许多powershell脚本,并且我想将所有Catch代码块拉到列表/变量中.

I'm trying to analyse lots of powershell scripts in a number of directories and i want to pull any Catch code blocks into a list/ variable.

我正在尝试编写正则表达式以选择以下格式的任何块

I'm trying to write a regex to select any block in the following formats

    Catch 
        {
        write-Host "Function:",$MyInvocation.MyCommand,"Failed with exception:" "Error"
        write-Host "Exception: $_" "Error"
        throw "Exception: $_"
        }

    Catch{
        write-Host "Function:",$MyInvocation.MyCommand,"Failed with exception:" "Error"
        write-Host "Exception: $_" "Error"
        throw "Exception: $_" }
Catch {write-Host "Function:",$MyInvocation.MyCommand,"Failed with exception:" "Error"
        write-Host "Exception: $_" "Error"
        throw "Exception: $_"}

基本上在任何地方都有一个接住{}的字符,将忽略单词"Catch"和花括号之间以及花括号之后的换行符,忽略大小写.

Essentially anywhere there is a catch followed by {}, ignoring any line breaks between the word "Catch" and the braces and after the braces, ignoring case.

我也希望返回{}之间的全部内容,以便我可以对其进行一些其他检查.

I want the entire contents between the {} returned too so i can do some additional checks on it.

我想出的最好的办法是:

The best i have managed to come up with is:


\b(\w*Catch\w*)\b.*\w*{\w.*}

如果全部在一行上,则将匹配.

Which will match if its all on one line.

我将在powershell中执行此操作,因此将非常感谢.net或powershell类型的正则表达式.

I'll be doing this in powershell so .net or powershell type regex would be appreciated.

谢谢.

推荐答案

不要使用正则表达式在PowerShell中解析PowerShell代码

改为使用PowerShell解析器!

Don't use regex to parse PowerShell code in PowerShell

Use the PowerShell parser instead!

foreach($file in Get-ChildItem *.ps1){
    $ScriptAST = [System.Management.Automation.Language.Parser]::ParseFile($file.FullName, [ref]$null, [ref]$null)

    $AllCatchBlocks = $ScriptAST.FindAll({param($Ast) $Ast -is [System.Management.Automation.Language.CatchClauseAst]}, $true)

    foreach($catch in $AllCatchBlocks){
        # The catch body that you're trying to capture
        $catch.Body.Extent.Text

        # The "Extent" property also holds metadata like the line number and caret index
        $catch.Body.Extent.StartLineNumber
    }
}

这篇关于我如何选择“捕获"?在PowerShell中使用正则表达式的代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 18:10