This is still helpful in late 2024 and early 2025 I was overlooking the restart after adding the M2 and M2_HOME variables.
Command Prompt was able was able to find the maven version and path without the two variables but git bash and power shell were having issues in VS Code.
The restart cured this after adding the variables.