VS2010: How to use Environment Variables in Post-Build

删除回忆录丶 提交于 2021-02-15 03:53:00

问题


On my PC I have created a system environment variable called 3DSMaxInstallDirectory

At the command line, if I give

echo %3DSMaxInstallDirectory%Plugins\

I get

D:\Program Files\Autodesk\3ds Max 2011\Plugins\

In Visual Studio I enter into the Post-Build section

copy "$(TargetDir)$(TargetName).*" "$(3DSMaxInstallDirectory)Plugins\"

However on build I get

Error   4   The command "copy "C:\Users\Sebastian\Documents\Visual Studio 2010\Projects\MaxBridge\MaxBridgeImporterPlugin\bin\Debug\MaxBridgePlugin.*" "Plugins\"
" exited with code 1.   MaxBridgeImporterPlugin

The results on Google are a confusing mix of suggestions that Visual Studio doesn't support EVs, Visual Studio does support EVs, Visual Studio needs %..% and Visual Studio needs $(..) - and none of which seem to work on my computer.

What is the correct way to use my environment variable in Visual Studio?

(Yes, the directory exists, and the reason I don't want to set the path explicitly is I am preparing to share this project, and every step someone else has to take after downloading and before building is another barrier.)


回答1:


This works for me in the Post-Build setting of the 'Build Events' of the project.

echo %CodeContractsInstallDir%
echo %DXSDK_DIR%
echo "%ONLYME%"

ONLYME is a environment var in the User variables of my profile.

The others are System wide vars.

ONLYME stays empty if I start VS2010 as administrator, the systemvars still have values as expected.

I'm on V2010 SP1




回答2:


The '%' character is reserved by MSBuild, so you have to replace it by the %25 hexadecimal escape sequence as documented in MSDN.

copy "$(TargetDir)$(TargetName).*" "%253DSMaxInstallDirectory%25\Plugins" should actually work. However: Visual Studio's commandline editor displays it correctly, but MSBuild then interprets %253 wrongly. I can't tell whether it's a bug or a feature but you must not start your environment variable's name with a digit.




回答3:


Visual studio doesn't properly encode/decode "special" characters in the XML config file. I'm able to get it to work as expected by manually escaping the command as a URL (http://www.w3schools.com/tags/ref_urlencode.asp).

ECHO %CD%

Results in an output log:

Target "PreBuildEvent" in file "blahblahblah"
    Task "Exec"
        Command:
        ECHO %CD%
        C:\blah\blah\blah\Debug
    Done executing task "Exec".

However, using URL escapes in the project proerties dialog appears to work:

ECHO %25CD%25


来源:https://stackoverflow.com/questions/18042632/vs2010-how-to-use-environment-variables-in-post-build

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!