nightroman / Invoke-Build

Build Automation in PowerShell

Home Page:https://github.com/nightroman/Invoke-Build/wiki

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Getting Task name from another task.

jdispiritoae opened this issue · comments

Is it possible to get the name of the task that called a task?

Take this code for example:

task BuildAll Step1 Step2 Step3

When running Step1, is it possible to get the name "BuildAll" from a predefined variable?
I would like to be able to retrieve a value in a hash table with the key name of a task.

Have you closed the issue by mistake or because you found an answer?

Anyway, every task has the automatic variable $Task defined by the build engine.
The current task may access its variable directly as $Task.
To get the parent task variable use Get-Variable Task -Scope 2 -ErrorAction 0.

-ErrorAction 0 is used to avoid an error when the parent task does not exist.
And you have to check the result for $null ~ the parent task does not exist.

Example script.
Tasks step1 and step2 print their own name and the parent task name

task buildAll step1, step2

task step1 step2, {
    # this task
    $Task.Name

    # parent task
    $varParentTask = Get-Variable Task -Scope 2 -ErrorAction 0
    if ($varParentTask) {
        $varParentTask.Value.Name
    }
}

task step2 {
    $Task.Name

    # parent task
    $varParentTask = Get-Variable Task -Scope 2 -ErrorAction 0
    if ($varParentTask) {
        $varParentTask.Value.Name
    }
}

Output on Invoke-Build buildAll

Build buildAll C:\tmp\_210831_7h-ib\.build.ps1
Task /buildAll/step1/step2
step2
step1
Done /buildAll/step1/step2 00:00:00.0312363
Task /buildAll/step1
step1
buildAll
Done /buildAll/step1 00:00:00.0468662
Done /buildAll/step2
Done /buildAll 00:00:00.0624952
Build succeeded. 3 tasks, 0 errors, 0 warnings 00:00:00.2969197

Thanks for the detailed explanation. I had closed the ticket because in my testing I found the variable $BuildTask, and that contained the task information I needed to use for my hash table lookup.

Invoke-Build is a powerful tool! Thanks for writing it!

Good and thank you!

A word of caution. See my example. The command is Invoke-Build buildAll so $BuildTask contains just buildAll. And the task step2 "does not know" that it is actually called by step1. This may or may not be important in your scenario, indeed.

A side thought/question - why do you need to know a parent/calling task? In theory, idiomatically, etc. tasks are things on their own. They may depend on script parameters. But depending on a caller is rather unusual (I am not saying "wrong").