0

I have a problem with adding VBScript to a Batch file. I tried this:

@echo off
echo MsgBox("Hello")
echo Do
echo MsgBox("Hello")
echo Loop >>msg2.vbs
start msg2.vbs

But it gave me an error that I used Loop without Do. What am I doing wrong?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • 1
    There is no need to use a temporary vbs file. You can embed and execute vbs code directly within your batch script. Have a look at http://stackoverflow.com/q/9074476/1012053 – dbenham Apr 16 '17 at 22:35
  • 1
    Possible duplicate of [Is it possible to embed and execute VBScript within a batch file without using a temporary file?](http://stackoverflow.com/questions/9074476/is-it-possible-to-embed-and-execute-vbscript-within-a-batch-file-without-using-a) – user692942 Apr 17 '17 at 08:49
  • @dbenham Just because you *can* insert sharp and pointy objects into your body doesn't mean you *should*. – Ansgar Wiechers Apr 18 '17 at 15:48
  • but @dbenham i `want`. – Anonymous 1582 Apr 18 '17 at 16:57
  • I never meant to imply that there is something wrong with using a temporary file. I was simply pointing out there is another option. – dbenham Apr 18 '17 at 17:14
  • @dbenham I was half-joking. However, at the end of the day I do consider these Frankenscripts problematic, because they're harder to understand, troubleshoot, and maintain than separate scripts. As a sysadmin I believe we should refrain from making things more complicated than they need to be for the person coming after us. – Ansgar Wiechers Apr 18 '17 at 18:54

2 Answers2

1

Your batch file doesn't magically know which lines you want in the VBScript. Either redirect each echo output (as agriffaut suggested), or run the echo statements in a command block and redirect the entire output of that block (so you don't have to append repeatedly):

(
  echo MsgBox("Hello"^)
  echo Do
  echo MsgBox("Hello"^)
  echo Loop
)>msg2.vbs

Note that for the latter you need to escape closing parentheses inside the block. In this particular case you could just remove them entirely, though:

(
  echo MsgBox "Hello"
  echo Do
  echo MsgBox "Hello"
  echo Loop
)>msg2.vbs

Another option would be using a single echo statement and escaping the line breaks:

>msg2.vbs echo MsgBox "Hello"^

Do^

MsgBox "Hello"^

Loop

Note that the blank lines are required here.

Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
0

Your Batch script actually only append loop to msg2.vbs file on each run..

You should append all 'vbs' lines from your batch file like this:

@echo off
echo msgBox("Hello") > msg2.vbs    :: > creates file if not exists with: msgBox("Hello")
echo do >> msg2.vbs                :: >> appends line with: do
echo msgBox("Hello") >> msg2.vbs   :: >> appends line with: msgBox("Hello") 
echo loop >> msg2.vbs              :: >> appends line with: loop
start msg2.vbs
agriffaut
  • 16
  • 2