Please feel free to provide feedback or file bugs here.

Powershell not interpreting spaces correctly

I am running a powershell script in the Post-Build event in Visual Studio (VS). Here is a simplified version of the command command

powershell -ExecutionPolicy remotesigned -File "%SampleDir%\update.ps1" "$(ProjectDir)" "$(TargetName)" "$(TargetExt)" "$(Configuration)"

I want you to understand that I have no control of these macro's $(ProjectDir) ... VS will fill these in.

To simplify things I've eliminated VS. Here is a script that simply echo's the input given to it. This will show the problem copy the below script to a file called echo-args.ps1
#===================================
"The number of parameters passed in is $($Args.Count)"
$i = 0
foreach ($arg in $Args) { echo "The $i parameter is $arg"; $i++ }
#===================================

Whether the script is invoked as

## works as expected
1) & "$env:SampleDir\echo-args.ps1" "D:\Users\robertla\Documents\Visual Studio 2017\Samples\Debug_Utilities\" "Debug Utilities" ".dll" "Debug"

or the below invocation which is how it needs to be invoked inside of the VS Post-Build event environment
## doesn't handle spaces correctly
2) powershell -ExecutionPolicy remotesigned -File "$env:SampleDir\echo-args.ps1" "D:\Users\robertla\Documents\Visual Studio 2017\Samples\Debug_Utilities\" "Debug Utilities" ".dll" "Debug"

This is the output from 2) which you can see is incorrect
The number of parameters passed in is 2
The 0 parameter is D:\Users\robertla\Documents\Visual Studio 2017\Samples\Debug_Utilities" Debug
The 1 parameter is Utilities .dll Debug

I wanted to show you that the output of 1) is not the same as the output of 2). However VS will spawn CMD.EXE and pass in the command line provided in the Post-Build event. This test really needs to be done in NT's shell.

Replace $env:SampleDir with %SampleDir% and rerun the 2) in CMD.EXE.

You should also checkout the behavior when single quotes are used rather than double quotes. Both are incorrect but in different ways

1 vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    Signed in as (Sign out)

    We’ll send you updates on this idea

    Bob Landau shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    0 comments

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      Signed in as (Sign out)
      Submitting...

      Feedback and Knowledge Base