consultancy chorley ASP.NET Server Side Scripting Wigan
Website Development Radcliffe

A Coder's Notes

Email :
bespoke invoice systems Standish Information Technology Advice Worsley
    development systems Ramsbottom
data manipulation Farnworth access databases Whitefield SQL connections Atherton
online accessible software Leyland software compatible Coppull

Get connected and Online Tottington
remote management Makerfield code and design Aspull

Batch Files, Ampersands & Escaping - 09/11/2010

OMG Batch files should be soooo simple yet the tiniest thing can be soooo complex!

Imagine if you will, you wish to insert the following string into a file from a file

echo Hello >> test.test

That command works just fine, you'll get a file called test.text and if you open that file with notepad then it will simply read "Hello"

now imagine you wish to enter the follwing string into the same file, in this case the string is a URL that is dynamically built in a .VBS script

echo url = "" & user.text & "&time=" & time.text >>test.vbs

Logic would dictate that you would end up with a file called "test.vbs" and inside that file will be the text url = "" & user.text & "&time=" & time.text >>test.vbs

but no, you will get the following error

echo url = ""
'user.text' is not recognized as an internal or external command,
operable program or batch file

'"time="' is not recognized as an internal or external command,
operable program or batch file

So first of...what's the issue?  The Ampersand, "&" is part of the DOS, Commandline, Batch programming language.  Now TONS and TONS of helpful websites state that ampersands can be "escaped", that means treated as an ampersand and not a command by using the "caret" beforehand.  The caret is "^" or on a UK keyboard, shift-6

So I try the following command
echo url = "" ^& user.text ^& "^&time=" ^& time.text >>test.vbs

And still get the exact same error.  Grrrrrrr!  So I mess around for ages and ages and ages, then I try the following...

echo url = "" ^&^ user.text ^&^ "&time=" ^&^ time.text >>test.vbs

WAHOO!  It works!  What ALL the other website negect to mention that the caret ^ only works before the & IF there's no white space AFTER the &


echo Hello one ^&all

will work, yet

echo Hello one ^& all

Will not work..but what will work is

echo Hello one ^&^ all

How strange is that...still no-one said it was easy.  Also it's good to note there's some funny quirks as to whether the ampersand is within speech marks or not.  Go play...but remember ^&^!

Post A Comment

Name Comment
programming services specialist
Valid XHTML 1.0 Transitional