tasks.getByName is a very bad idea, as it breaks task-configuration avoidance.
Better would be tasks.named("...") { enabled = false } but it will have the same problem as it also only works if the task is already registered, but it seems that task is only executed later.
To correctly disable even if registered later, you would use tasks.named { it == "..."}.configureEach { enabled = false }.
But be aware that enabled = false is not the same as -x. -x completely removes the task from the task list so also the tasks it depends on are not executed unless also depended upon by some other task. enabled = false just disables the actions for that task, but the dependencies are still executed.
In older version you can instead do .matching { it.name == "..." }.configureEach { ... }.
Is there a way to mimic -x with the configuration?
Add to gradle.startParameter.excludedTaskNames, that is where -x arguments land and as long as you do it during configuration phase it is effective as it is only evaluated by Gradle after configuration phase.