开发者

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

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 o开发者_高级运维nly permitted one statement between the IF parenthesis?

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜