0

I tried the following code:
set target = "%~dp0\Backup1"
set /s checktarget = %1
for %%I in (%*) do (
   if "%checktarget:~0,3%" == "tg." (
       set target = %checktarget:~4:3%
   ) else ( echo "%%I to %target%" )
)

My goal was to check if the first parameter is a destination for a backup.
The destination is supposed to come with a "tg.", followed by a directory. I run my script with:

test.bat tg.target B1 B2 B3

But when i run this, the output is:

"tg.target to "
"B1 to "
"B2 to "
"B3 to "

What i want it to be is:

"B1 to target"
"B2 to target"
"B3 to target"

I've tried looking for a way to fix this for several hours now. Does anyone know why it just gives me "" as a target? It doesn't even use the target thats set as a default.

  • 2
    The first thing you should implement is a safer method of passing arguments to the batch file. i.e. `"test.bat" "tg.target" "B1" "B2" "B3"`. Once you've done that, you should be able to retrieve each of those arguments in the batch file, without those enclosing doublequotes, as `%~0` -> `test.bat`, `%~1` -> `tg.target`, `%~2` -> `B1`, `%~3` -> `B2`, and `%~4` -> `B3`. Then you should learn how to more safely define a variable with a value, `Set "VariableName=VariableValue"`. _(e.g. `Set "target=%~dp0Backup1"` noting that `%~dp0` already has a trailing backward slash)_. – Compo May 13 '21 at 23:11
  • 1
    You should then take a look to see if you have a typo here, `%checktarget:~4:3%`, because I don't think that the `:` character is usual when expanding variables. Also whether you have another here, `set /s`, because I don't remember ever seeing an `/S` option. Once all of that is done, you question will be a duplicate, because you have a delayed expansion issue. – Compo May 13 '21 at 23:14
  • 1
    There should be no spaces around the equals symbol in `set target = %checktarget:~4:3%`. What have there is a variable named target with a space on the end of it and your are setting it to a value that starts with a space. Probably not what you intended. – jwdonahue May 13 '21 at 23:42
  • 1
    Try `help setlocal`, `help set` and `help if`. – jwdonahue May 13 '21 at 23:43

0 Answers0