Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Anonymous Recursive Function

Is it possible to create an anonymous Recursive Function in PowerShell? (if yes, how?)

I have a recursive object and using a recursive function to drill down through the properties, like:

$Object = ConvertFrom-Json '
{
    "Name" : "Level1",
    "Folder" : {
        "Name" : "Level2",
        "Folder" : {
            Name : "Level3"
        }       
    }
}'

Function GetPath($Object) {
    $Object.Name
    if ($Object.Folder) { GetPath $Object.Folder }
}

(GetPath($Object)) -Join '\'

Level1\Level2\Level3

The function is relative small and only required ones, therefore I would like to directly invoke it as an anonymous function, some like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(&{
    $Object.Name
    if ($Object.Folder) { ???? $Object.Folder }
}) -Join '\'

Is this possible in PowerShell?
If yes, how can I (as clean as possible) refer to the current function at ?????

>Solution :

Unfortunately there is not much documentation on this topic but you could execute the anonymous script block by calling $MyInvocation.MyCommand.ScriptBlock, a simple example:

&{
    param([int] $i)

    if($i -eq 10) { return $i }
    ($i++)
    & $MyInvocation.MyCommand.ScriptBlock $i
}

# Results in 0..10

Using your current code and Json as example:

(&{
    param($s)

    $s.Name
    if ($s.Folder) { & $MyInvocation.MyCommand.ScriptBlock $s.Folder }
} $Object) -Join '\'

# Results in Level1\Level2\Level3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading