Rather than bother with custom groovy to hack the Jenkins declarative pipeline environment, let's use a structural paradigm that has been successful for me because of its simplicity (the only cost being a reusable custom groovy function) and readability (the function wrapper demonstrates what it does in salutary clarity).
int withVSEnvironment(String label, Boolean returnStatus, String script) { ret = powershell( label: label, returnStatus: returnStatus, script: """ foreach (\$_ in cmd /c "`"%VS140COMNTOOLS%`"..\\..\\vc\\bin\\vcvars32.bat > nul 2>&1 & SET") { if (\$_ -match '^([^=]+)=(.*)') { [System.Environment]::SetEnvironmentVariable(\$matches[1], \$matches[2]) } } $script """ ) if (returnStatus) { return ret } } pipeline { agent any stages { stage('Stage Left') { steps { withVSEnvironment( 'Building with PowerShell!!!', False, // returnStatus ''' # No weak cmd script here MSBuild.exe Source/Answer/The_Solution.sln /m /t:Clean,Rebuild ''' ) } } } }