EMP
EMP

Reputation: 61971

How to set PATH to another variable value with spaces in Windows batch file

I've got a Windows batch script issue that I'm bashing my head against (no pun intended). The problematic script looks like this:

if defined _OLD_VIRTUAL_PATH (
    set PATH=%_OLD_VIRTUAL_PATH%
)

When I run it and _OLD_VIRTUAL_PATH is set I get:

\Microsoft was unexpected at this time.

_OLD_VIRTUAL_PATH is a variable that was originally set from PATH and it contains spaces - I'm pretty sure that's the problem. But what's the solution? It runs successfully if I enclose it in quotes, but I don't think the entire value of the PATH variable is supposed to be in quotes.

Upvotes: 5

Views: 3780

Answers (2)

Chris Schmich
Chris Schmich

Reputation: 29466

Your problem here are not the spaces but rather a closing parenthesis. You are probably running a 64-bit system where the Program Files directory for 32-bit applications is Program Files (x86). In a parenthesized block in a batch file, the closing parenthesis ends the block, so the rest of the line causes a syntax error.

You have two ways to fix this:

1) Put the complete set argument in quotes. This causes the closing paren to not be recognized as end of block:

if defined _OLD_VIRTUAL_PATH (
    set "PATH=%_OLD_VIRTUAL_PATH%"
)

2) Don't use a block:

if defined _OLD_VIRTUAL_PATH set PATH=%_OLD_VIRTUAL_PATH%

Upvotes: 7

Michael Burr
Michael Burr

Reputation: 340178

Well - I never knew about the defined operation in cmd scripts until just now...

Your script seems to work fine for me - which line exactly is producing the error?

You can also try:

if not "%_OLD_VIRTUAL_PATH%" == "" (
    set PATH=%_OLD_VIRTUAL_PATH%
)

And believe me, if you're coming into Windows cmd scripting expecting it to be anything like what you have in bash, your head will be very much in pain, very soon. You might want to look into using some other scripting language (PowerShell, Python, PERL - anything) if cmd scripting isn't an absolute requirement. the biggest thing (maybe the only thing) that cmd scripting has going for it is that it's already installed on every Windows box.

Upvotes: 0

Related Questions