Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch file IF statement fails with "was unexpected at this time"

Tags:

batch-file

I have a batch file that does the following:

@IF EXIST "C:\Program Files\MyAppFolder" (
  icacls "C:\Program Files\MyAppFolder" /inheritance:r
  icacls "C:\Program Files\MyAppFolder" /GRANT SYSTEM:(CI)(OI)(F)
  icacls "C:\Program Files\MyAppFolder" /GRANT Administrators:(CI)(OI)(F)
)

Individually the commands work fine but put together like this in an IF statement I get this error and the script stops in its tracks:

(OI)(F) was unexpected at this time.

If I just have a single command in the IF statement then it works fine.

I'm guessing that you're only permitted one statement between the IF parenthesis?

This happens on Windows 2008 and Windows 2003 (with the ICACLS hotfix).

like image 966
Kev Avatar asked Jun 25 '11 15:06

Kev


People also ask

Was unexpected at this time batch error?

If you are getting this error on your IF statement check if used or not your double equals to compare your variable. Eg. This throws "=1 was unexpected at this time." To correct this add another equals sign.

What does %1 do in batch?

When used in a command line, script, or batch file, %1 is used to represent a variable or matched string. For example, in a Microsoft batch file, %1 can print what is entered after the batch file name.

Can you use if statements in batch files?

One of the common uses for the 'if' statement in Batch Script is for checking variables which are set in Batch Script itself. The evaluation of the 'if' statement can be done for both strings and numbers.

Does batch have else if?

However, you can't use else if in batch scripting. Instead, simply add a series of if statements: if %x%==5 if %y%==5 (echo "Both x and y equal 5.") if %x%==10 if %y%==10 (echo "Both x and y equal 10.") else (echo "Invalid input.")


1 Answers

The shell seems to think that the ) in the third line of your command is the closing parenthesis for the one opened in the first line. You need to quote the arguments containing parenthesis:

@IF EXIST "C:\Program Files\MyAppFolder" (
  icacls "C:\Program Files\MyAppFolder" /inheritance:r
  icacls "C:\Program Files\MyAppFolder" /GRANT "SYSTEM:(CI)(OI)(F)"
  icacls "C:\Program Files\MyAppFolder" /GRANT "Administrators:(CI)(OI)(F)"
)
like image 111
sth Avatar answered Sep 28 '22 07:09

sth