1

I symplified my problem here:

@echo off

for %%a in (& ? !) do echo %%a

pause>nul

I want it to just print

&
?
!

but it doesn't work that way and rather takes an error

I know that the error is due to the special characters, but I don't know how to let them escape in that sentence.

I tried:

for %%a in "(& ? !)" do echo %%a
for %%a in ("& ? !") do echo %%a
for %%a "in (& ? !)" do echo %%a
for %%a in ("&" "?" "!") do echo %%a

and etc., but didn't find how

2
  • What version of WIndows? Why batch? If you're not already prficient in batch, no point in learning it now. Your time is most likely better spent learing PowerShell. Aug 8, 2020 at 2:32
  • I didn't even know what powershell is when I wrote this,,, ha. I am afraid I may confuse powershell with batch when learning powershell again.
    – shiftdel
    Aug 8, 2020 at 7:40

1 Answer 1

1

As you have noticed, some characters are interpreted by the Windows command processor as having special meanings for use in complex commands.

You must escape such characters for normal use.

The escape character for the Windows command processor is ^. Using this, you may escape almost all special characters, including the ampersand &. The only one that cannot be escaped is the question mark ?.

@echo off

for %%a in (^& !) do echo %%a

pause

Output:

&

!

For more advanced scripting, Windows now includes PowerShell, which you may use to overcome the problem. Enter the command

PowerShell

and you will see a new prompt. From the PowerShell prompt you may then use the following command to do what you need without any limitation on special characters:

foreach ($item in @("&", "?", "!")) { echo $item }

Output:

&

?

!

I have given a one-line example but just like the classic Windows command processor, PowerShell provides the abillity to batch up commands into scripts. As well as the main PowerShell reference, there is a good resource on scripting generally here, covering details of this kind in a helpful way.

2
  • Thank you, I learn that batch programming has many limits...
    – shiftdel
    Aug 8, 2020 at 3:51
  • Yes, but it is very simple and very powerful. I script in Powershell TOO.. sometimes batch is just easier depending on the task. I always have to look stuff up in Powershell but not in good 'ol (crappy) batch. Aug 8, 2020 at 4:06

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .