0

I'm trying to build a string in my batch script but I couldn't get it to working.

Here's what I'm trying:

@echo off
set str="wt -p "
for /r "C:\Documents\Files\" %%f in (*) do (
    set str=%str% "Command Prompt" cmd /k "echo %%f";new-tab -p
)
echo %str%
pause

wt -p command is supposed to open it in the new Windows Terminal instead of regular Command Prompt.

I want to specify that %%f which is the full path of the file does include blank spaces inside it. So the command should be accepting it.

I've always been struggling with creating batch scripts, it is overwhelming after some point too. What am I doing wrong here?

oividiosCaeremos
  • 608
  • 1
  • 10
  • 30
  • 1
    Remove the spaces around the `=` - they become part of the variable name and the value. But honestly: I have no idea, what `set str = %str% echo %%f"; new-tab -p ""` is supposed to do. It makes no sense to me. – Stephan Jul 29 '22 at 09:09
  • That didn't do anything. If we come to what I want to do, I want to dynamically open a new terminal screen and then for each file/directory in the `C:\Documents\Files` I want to add a new tab to that existing terminal and prompt the file name. That line may not work as it is now, and might need changes. @Stephan – oividiosCaeremos Jul 29 '22 at 09:27
  • The main problem is, I cannot get file paths to append to the `str` variable. `str` at the end is still equal to `wt -p` – oividiosCaeremos Jul 29 '22 at 09:50
  • @Stephan I updated the script there. Result I expect is to have `wt -p "Command Prompt" cmd /k "echo hello"; new-tab -p "Command Prompt" cmd /k "echo hello2"` at the last `echo` but what I get is `wt -p` – oividiosCaeremos Jul 29 '22 at 09:53
  • 2
    You'll need [delayed expansion](https://ss64.com/nt/delayedexpansion.html) for variable `str` since you read and write it within the `for /R` loop… – aschipfl Jul 29 '22 at 10:01

1 Answers1

1

When you want to use a variable that you defined/changed within a code block, you need delayed expansion.

@echo off
setlocal enabledelayedexpansion
set "str=wt -p "
or /r "C:\Documents\Files\" %%f in (*) do 
    set "str=!str!"Command Prompt" cmd /k "echo %%f";new-tab -p "
)
echo %str%
goto :eof
Stephan
  • 53,940
  • 10
  • 58
  • 91