Once you know the length of the folder path, then a simple substring is all you need - a standard feature of variable expansion.
It is easy to avoid problems with exclamation points and delayed expansion within a FOR loop if you toggle the delayed expansion on and off.
On my machine, the ICACLS command outputs a summation line at the end that must be ignored - Something like "Successfully processed 1 files; Failed processing 0 files" I could use FINDSTR to filter out lines that begin with "Successfully", but then I could not process a folder that begins with that value. So I use a trick to process the previous line within a loop, thus the last line is never processed.
I also redirect stderr to stdout so that you get nice output if you pass in an invalid path.
I avoid having to add one to the string length by appending an extra character to the variable definition.
Code: Select all
@echo off
setlocal disableDelayedExpansion
for %%F in (
"c:\Program Files (x86)"
"c:\Program Files\Common Files"
.
SomeInvalidPath
) do (
set "folder=x%%~F"
call :strLen len folder
echo CurrentFolder: __________ %%~F
set "ln="
for /f "eol=: delims=" %%A in ('icacls "%%~F" 2^>^&1') do (
if defined ln (
setlocal enableDelayedExpansion
for %%N in (!len!) do echo !ln:~%%N!
endlocal
)
set "ln=%%A"
)
echo(
)
exit /b
:strlen <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
exit /b
)
It is easy to solve the problem with JREPL with a minimal amount of code, but it really is actually significantly slower due to start up times for each JREPL instantiation. And it feels like I am going out of my way to use JREPL when the actual problem does not really call for regular expressions.
Code: Select all
@echo off
setlocal disableDelayedExpansion
for %%F in (
"c:\Program Files (x86)"
"c:\Program Files\Common Files"
.
someInvalidPath
) do (
echo CurrentFolder: __________ %%~F
for /f %%N in ('echo %%~F^|jrepl "^.*" "$0.length+1" /j') do (
icacls "%%~F" 2>&1 | jrepl ".{%%N}(.*)" "$1" /jmatch /exc -1
)
echo(
)
Dave Benham