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

Viewed 35464

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).

2 Answers

The above answer won't work if you need to assign permissions to a user with a space in their name (EG: "CREATOR OWNER")

A better solution is to use a function with call:

@ECHO OFF

IF EXIST "C:\Program Files\MyAppFolder" (
   CALL:Permissions
)

GOTO:eof

:Permissions
   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)
   GOTO:eof

The GOTO:eof is required at the end of the function.

Detailed information on functions in batch can be found here.

Related