How to escape spaces the parameters to a PS script running in VS post-build event How to escape spaces the parameters to a PS script running in VS post-build event powershell powershell

How to escape spaces the parameters to a PS script running in VS post-build event


Beware unexpected escaped quotes when a VS directory macro is expanded in a quoted parameter.


A script parameter containing a path should be wrapped in quotes to avoid being interpreted as multiple parameters if the path includes spaces. The following would therefore seem reasonable in Visual Studio's pre/post build event command line:-

powershell.exe -file "$(SolutionDir)script.ps1" -projectDirectory "$(ProjectDir)"

But the macro values that specify directories always include a trailing backslash; so when they're expanded the line becomes, for example:-

powershell.exe -file "C:\sln path\script.ps1" -projectDirectory "C:\sln path\project\"

...where the trailing \" is an escaped character that is interpreted as part of the parameter value, which is passed to the script as:-

C:\sln path\project"

Solution

The fix in my case was to insert an additional backslash after the directory macro to be escaped instead of the quotes, which restores the expected parameter value and prevents the mangling of any subsequent params:-

powershell.exe -file "$(SolutionDir)script.ps1" -projectDirectory "$(ProjectDir)\"

Not very intuitive though. Let me know if I'm missing something more obvious...


One thing I noticed is an extra backslash after $(SolutionDir). I'm using VS2017 and I think consistently $(SolutionDir) has always had a backslash. Not sure though.

I have a .bat in my solution folder that creates a json config file. My Post-Build event looks like this.

call "$(SolutionDir)CreateConfigurationJson.bat" "$(TargetDir)mySettings.json"{"ProjectName":"$(ProjectName)"}

"$(TargetDir)mySettings.json" is the first parameter of the .bat file

{"ProjectName":"$(ProjectName)"} is the second parameter.

No escape characters necessary. Hope this helps.

The code for the bat file is:

echo offset filePath=%1break>%filePath%set json=%2echo %json% >>%filePath%