islamadel / bat2exe

Automatically exported from code.google.com/p/bat2exe
257 stars 33 forks source link

Arguments passed to the EXE are doubled in the BAT #9

Open Saphareas opened 3 years ago

Saphareas commented 3 years ago

Arguemnts that are passed to the generated EXE file appear to be passed twice to the BAT script. My BAT looks like this "C:\Program Files\7-Zip\7zG.exe" x "%1" -o"C:\Users\myUser\Desktop\Entpackt\*" But when I run myexe.exe myDir\test.zip what is actually executed (I can see this in the error message) is this "C:\Program Files\7-Zip\7zG.exe" x "..\myDir\test.zip..\myDir\test.zip" -o"C:\Users\myUser\Desktop\Entpackt\*"

Note, that for "%1" in my script ..\myDir\test.zip..\myDir\test.zip gets inserted instead of ..\myDir\test.zip

reno3131 commented 3 years ago

A work around for those who encounter this problem.

FOR /f tokens^=1delims^=^" %%i IN ("%1") do ( set fullpath=%%~i set drive=%%~di set filepath=%%~pi set name=%%~ni set fileext=%%~xi )

This will explode %1 arg in usefull component and remove the double insertion. Not clean but functionnal. Use this just before using %1 and change %1 to %fullpath%, other component are there to manipulate the provided file name.

yjyao commented 3 years ago

ran into this today. @reno3131's solution did not work for me:

i was trying to invoke the converted exe as a default program to open certain type of files. apparently when Windows passes the filepath to the program it doesn't quote the filepath.

never worked with batch before, so my solution is probably stupid and ugly. but I thought i'd share anyway. i simply took half of the argument and tested if the argument is the same string repeated twice:

Rem Hack for bat2exe.
Rem ==========
Rem Bat2exe has a bug where it duplicates the argument. See https://github.com/islamadel/bat2exe/issues/9.
Rem For example, running
Rem     script.exe Hello
Rem would be equivalent as running
Rem     script.bat HelloHello
Rem To handle this, we take half of the argument and see if the argument is the
Rem half repeated twice. If that is the case, set "arg" to the half.

setlocal EnableDelayedExpansion

set arg=%1
call :strlen len arg
set /A len=%len%/2
call set arg_half=%%arg:~0,%len%%%
if !arg! == !arg_half!!arg_half! (set arg=%arg_half%)

Rem Fucntion that returns length of a string. See stackoverflow.com/a/5841187.
:strlen <resultVar> <stringVar>
(
  setlocal EnableDelayedExpansion
  (set^ tmp=!%~2!)
  if defined tmp (
    set "len=1"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
      if "!tmp:~%%P,1!" NEQ "" (
        set /a "len+=%%P"
        set "tmp=!tmp:~%%P!"
      )
    )
  ) ELSE (
    set len=0
  )
)
(
  endlocal
  set "%~1=%len%"
  exit /b
)

Use arg henceforth.