windowsbatch-file

Call batch function fails with path containing spaces and double quotes


I have a function that calls a program, it is trying to run a pkzipc with a path parameter that has double quotes and spaces. I have tried to escape spaces and quotes in different ways as mentioned in other posts like escaping it with quotes or caret and even no passing the quotes but nothing seems to make pkzipc to execute.

I tried passing the path like ""C:\Users\Test\OneDrive - Test Corp\Playground\testone.zip"", and tried call "%~2".

Here is the full script that I am trying to run.

@echo off

set "command=pkzipc -extract "C:\Users\Test\OneDrive - Test Corp\Playground\testone.zip" "C:\Users\Test\OneDrive - Test Corp\Playground\Extract""

call :myFunction "command1" "%command%"

echo Back in main script
exit /b

:myFunction
echo Inside myFunction
echo Argument 1: %~1
echo Argument 2: %~2
echo Starting command execution... %~2
call %~2

exit /b

Solution

  • Try:

    @ECHO OFF
    SETLOCAL
    
    set "command=pkzipc -extract "C:\Users\Test\OneDrive - Test Corp\Playground\testone.zip" "C:\Users\Test\OneDrive - Test Corp\Playground\Extract""
    
    call :myFunction "command1" command
    
    echo Back in main script
    GOTO :eof
    exit /b
    
    :myFunction
    echo Inside myFunction
    echo Argument 1: %~1
    CALL SET "arg2=%%%2%%"
    echo Argument 2: %arg2%
    echo Starting command execution... %arg2%
    ECHO call %arg2%
    
    exit /b
    GOTO :EOF
    
    

    Your syntax would deliver "pkzipc -extract "C:\Users\Test\OneDrive - Test Corp\Playground\testone.zip" "C:\Users\Test\OneDrive - Test Corp\Playground\Extract"" as the second parameter to the subroutine, so it is seen to be "pkzipc -extract "C:\Users\Test\OneDrive - a quoted string ("pkzipc -extract ") + some miscellaneous characters, terminated by a Space which is a separator.