user7645525
user7645525

Reputation: 23

Extracting the function body from a file using powershell

How can i extract the content of a powershell function definition? Suppose the code is like,

Function fun1($choice){
   switch($choice)
    {
       1{
        "within 1"
        }
       2{
        "within 2"
        }
       default{
        "within default"
        }

    }

}

fun1 1

I want only the contents of the function definition and no other text.

Upvotes: 2

Views: 860

Answers (1)

woxxom
woxxom

Reputation: 73616

Using PowerShell 3.0+ Language namespace AST parser:

$code = Get-Content -literal 'R:\source.ps1' -raw
$name = 'fun1'

$body = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null).
    Find([Func[Management.Automation.Language.Ast,bool]]{
        param ($ast)
        $ast.name -eq $name -and $ast.body
    }, $true) | ForEach {
        $_.body.extent.text
    }

Outputs a single multi-line string in $body:

{
   switch($choice)
    {
       1{
        "within 1"
        }
       2{
        "within 2"
        }
       default{
        "within default"
        }

    }

}

To extract the first function definition body regardless of name:

$body = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null).
    Find([Func[Management.Automation.Language.Ast,bool]]{$args[0].body}, $true) | ForEach {
        $_.body.extent.text
    }

To extract the entire function definition starting with function keyword, use $_.extent.text:

$fun = [Management.Automation.Language.Parser]::ParseInput($code, [ref]$null, [ref]$null).
    Find([Func[Management.Automation.Language.Ast,bool]]{$args[0].body}, $true) | ForEach {
        $_.extent.text
    }

Upvotes: 3

Related Questions