RegEx/PowerShell/ScriptBlock.regex.txt

# Matches a PowerShell script block
\{
\s{0,}
(?:
\<\# # The opening tag
(?<Help>
    (?:.|\s)+?(?=\#>) # anything until the closing tag
)
\#\> # the closing tag
)?
\s{0,}
(?:
    \s{0,}
    (?<Attributes>?<PowerShell_Attribute>([))
    \s{0,}
){0,}
\s{0,}
(?<ParamBlock>
param?<BalancedCode>{(}
)?
(?:
    \s{0,}
    (?<BeginBlock>begin\s{0,}
    (?<BeginScriptBlock>?<BalancedCode>({)))
    \s{0,}
)?
(?:
    \s{0,}
    (?<ProcessBlock>process\s{0,}
    (?<ProcessScriptBlock>?<BalancedCode>({)))
    \s{0,}
)?
(?:
    \s{0,}
    (?<EndBlock>end\s{0,}
        (?<EndScriptBlock>?<BalancedCode>({)))
    \s{0,}
)?
(?(BeginBlock|ProcessBlock|EndBlock) # If we have a begin, process, or end
    (?:\}) # then match but don't capture the closing }
    | # otherwise, assume we're in an end block
    (?<EndBlock> # An open bracket
        (?> # Followed by...
            [^\{\}]+| # any number of non-bracket character OR
            \{(?<Depth>)| # an open bracket (in which case increment depth) OR
            \}(?<-Depth>) # a closed bracket (in which case decrement depth)
        )*(?(Depth)(?!)) # until depth is 0.
    )\} # followed by a closing bracket))
)