Batch-Hell with empty space in filepath

Viewed 133

currently I am in the batch-hell. I want to call my powershell script via a batch file. This works properly as long as there are no empty spaces in the path. For example this is working

          set DATAPATH="%~1"
    set XMLFILE="%~2"
    set PSFILE="C:\dev\workflow\handler.ps1"
    echo %PSFILE%
    echo powershell -command %PSFILE% -datapath """%DATAPATH%""" -xmlFile """%XMLFILE%"""
    powershell -command %PSFILE% -datapath """%DATAPATH%""" -xmlFile """%XMLFILE%"""
    IF %ERRORLEVEL% == 0 (echo true) else (echo false)

When I change it to use a path which contains a space in the file path it is not working.

    set DATAPATH="%~1"
    set XMLFILE="%~2"
    set PSFILE="C:\dev\work flow\handler.ps1"
    echo %PSFILE%
    echo powershell -command %PSFILE% -datapath """%DATAPATH%""" -xmlFile """%XMLFILE%"""
    powershell -command %PSFILE% -datapath """%DATAPATH%""" -xmlFile """%XMLFILE%"""
    IF %ERRORLEVEL% == 0 (echo true) else (echo false)

The error message "C:\dev\work" was not not found as a name of a cmdlet indicates for me that the space is the root of the problem. Any idea I tried it also to define the variable PSFILE like this

set PSFILE="""C:\dev\work flow\handler.ps1"""

Maybe someone knows a solution and shows me how to handle spaces in a batch file path.

enter image description here

2 Answers

You should use the extended SET-syntax, set "DATAPATH=%~1" the quotes are BEFORE the variable name and at the end of the content.
This will set the content without quotes to the variable and avoids trailing invisble white spaces.

The you can use the variables with surrounded quotes.

powershell -File "%PSFILE%" -datapath "%DATAPATH%" -xmlFile "%XMLFILE%"

-File instead of -command seems to work, see also How to run powershell script from batch file while the ps script path has spaces and path is derived from %~dp0

cmd sees whitespace as the the separator between commands and paramters. So you need:

    set "DATAPATH=%~1"
    set "XMLFILE=%~2"
    set "PSFILE=C:\dev\work flow\handler.ps1"
    echo "%PSFILE%"
    echo powershell -file "%PSFILE%" -datapath "%DATAPATH%" -xmlFile "%XMLFILE%"
    powershell -file "%PSFILE%" -datapath "%DATAPATH%" -xmlFile "%XMLFILE%"
    IF %ERRORLEVEL% equ 0 (echo true) else (echo false)

Note the double quotes starts before the variable and end at the end of the variable.

Also note equ used instead of == in the if statement.

Related