Correct way to exclude a task from GradleBuild

It is possible to specify excluded tasks in this way

task publish(type: GradleBuild) {
    tasks = ['clean', 'build']
    getStartParameter().setExcludedTaskNames(['test']);
}

But why if the task is

task publish(type: GradleBuild) {
    tasks = ['clean', 'build']
}

And we run gradle publish -x test test is not excluded?

A GradleBuild task is executing a separate build. The test task would be excluded from the build that you run directly, not the build being run by your publish task.

The excluded tasks are not automatically inherited from the parent build. However, if you would like to propagate these options down, it is easy to do so without hardcoding the exclusion:

task publish(type: GradleBuild) {
    tasks = ['clean', 'build']
    startParameter.excludedTaskNames = gradle.startParameter.excludedTaskNames
}