MSbuild doesn't expand environment variables

2020-07-24 03:39发布

I'm using MSBuild to build a solution file from the command line. In it, the path to the vcxproj file is specified by an environment variable FOO by %FOO%\ProjName.vcxproj

When I open the sln in the IDE, I the project is found and loaded. When I use msbuild from the command line (on the same machine) I get an error of:

The Project File "C:\Blah\Blah\%FOO%\ProjName.vcxproj" was not found,

In the same command prompt

echo %FOO%  

Gives me the correctly expanded path.

标签: msbuild
2条回答
▲ chillily
2楼-- · 2020-07-24 04:06

From the comments; this is a known bug and a wontfix from MS. I ended up writing a batch file to copy the sln file and expand the environment variables, build that, and delete the new sln. Works fine.

查看更多
老娘就宠你
3楼-- · 2020-07-24 04:25

As @maccard stated, this is a known bug. (See https://developercommunity.visualstudio.com/content/problem/248631/msbuild-doesnt-parse-environment-variables-in-sln.html and https://github.com/Microsoft/msbuild/issues/120 )

You can use the following script to replace all environment variables in a .sln file with their values. (Script is only very lightly tested).

# Python 2.7
# usage: python fix_sln.py path/to/file.sln


import codecs
import os
import re
import shutil
import sys

if __name__ == "__main__":
    with codecs.open(sys.argv[1], encoding='utf-8-sig') as orig:
        with codecs.open(sys.argv[1] + '.modified', 'w', encoding='utf-8-sig') as new:
            for line in orig:
                line = line.rstrip('\r\n')
                found = re.search(r"""%.+%""", line)
                line = line.replace(str(found.group()), os.environ.get(str(found.group()).replace("""%""", ""))) if found else line
                new.write(line + '\r\n')
    shutil.move(sys.argv[1] + '.modified', sys.argv[1])
查看更多
登录 后发表回答