How to exclude sub-directory from cacls processing in batch file

4.9k views Asked by At

Suppose I have a directory myDir tree with many nested sub-directories. I grant full access to this directory with all its files and nested sub-directories to myUser with command:

cacls myDir /T /E /G myUser:F

So far, so good.

Now I have a sub-directory myDir/A/B/C which I would like to exclude from the cacls processing. That is, I would not like to grant myUser access to this sub-directory.

What would you suggest?

The simplest way is just to move this folder to another place before running cacls and move it back after that. Does it make sense?

2

There are 2 answers

0
joeking On

You need to generate a list of files to be processed and exclude the ones you don't want since CACLS doesn't allow filtering.

Here, I use "dir" to generate the list of files to process. You could use "forfiles" as well.

(You can make the script more compact using pipes, but I used temporary files instead just to make it more clear).

@echo off
setlocal

set TMPFILE=%TEMP%\dirs.txt
set TMPFILE2=%TEMP%\dirs2.txt

@rem Generate the list of dir names to be processed
dir "%~1" /ad /s /b /p > %TMPFILE%

@rem Filter out the unwanted ones
findstr /i /v /C:"myDir\A\B\C" < %TMPFILE% > %TMPFILE2%

@rem And execute a command on each
for /F "delims=;" %%x in (%TMPFILE2%) do call :dostuff "%%x"

goto :EOF

:dostuff
    @rem do the directory itself
    cacls "%~1\ /E /G myUser:F

    @rem do the files
    cacls "%~1\*" /E /G myUser:F

    goto :EOF
1
Endoro On

Inherited folder permissions are displayed as:

OI - Object inherit - This folder and files. (no inheritance to subfolders)
CI - Container inherit - This folder and subfolders.
IO - Inherit only - The ACE does not apply to the current file/directory

These can be combined as folllows:
(OI)(CI) This folder, subfolders, and files.
(OI)(CI)(IO) Subfolders and files only.
(CI)(IO) Subfolders only.
(OI) (IO) Files only.

So BUILTIN\Administrators:(OI)(CI)F means that both files and Subdirectories will inherit 'F' (Fullcontrol)
similarly (CI)R means Directories will inherit 'R' (Read folders only = List permission)

To actually change the inheritance of a folder/directory use iCACLS /grant or iCACLs /deny