2

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.

wOxxOm
  • 65,848
  • 11
  • 132
  • 136

1 Answers1

3

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
    }
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Thanks for your answer. could you suggest some sites/blogs to learn more about this? – user7645525 Mar 02 '17 at 08:26
  • I don't remember but I think I found some examples in C# and adapted them. Maybe those in the MSDN documentation linked in my answer. – wOxxOm Mar 02 '17 at 08:35