Search code examples
powershellmsbuildescapingpsake

How do I escape a directory correctly when using psake, exec, and msbuild?


I can execute the following command in PowerShell:

msbuild "c:\some\spaced path\project.sln" /p:MvcBuildViews=False /p:OutDir="c:\\some\\spaced path\\deploy\\Package\\"

The paths are changed, but the real ones also contain a spaced component. The double-slash is a trick from e.g. this answer.

If I run that directly, msbuild understands the path. However, it needs to run in psake like this:

exec { msbuild $SolutionFile "/p:MvcBuildViews=False;OutDir=$OutputDir" }

That works if the path has no spaces, but I want to adapt it to work with spaces (for both the sln path and OutDir). I've tried, but I couldn't figure out the escaping.

EDIT:

To clarify, it also works if I hard-code the full path in psake:

exec { msbuild "c:\some\spaced path\project.sln" /p:MvcBuildViews=False /p:OutDir="c:\\some\\spaced path\\deploy\\Package\\" }

However, it needs to use the OutputDir variable (which is not double-slash escaped). So, I add a temporary variable for that, then try to construct the command line.:

$double_slashed_dir = $OutputDir.Replace('\', '\\');
write $double_slashed_dir;
exec { msbuild $SolutionFile /p:MvcBuildViews=False "/p:OutDir=`"$double_slashed_dir`"" }

This doesn't work (I've tried a couple variations). With the above I get "MSB1008: Only one project can be specified."


Solution

  • This variation worked for me (double slashes and trailing slashes in $OutputDir seem to be important):

    task build {
        $SolutionFile = "C:\TEMP\spaced path\ConsoleApplication1.sln"
        $OutputDir = "C:\\TEMP\\spaced path2\\"
        exec { msbuild $SolutionFile "/p:MvcBuildViews=False;OutDir=$OutputDir" }
    }