loopsbatch-fileicacls

Batch File looping until certain text is displayed


Currently have a batch file for replacing NTFS permissions using the takeown and icacls commands, i have added these commands to a loop and it works great.

Is there a way to exit the loop when a certain response is displayed? like "Failed processing 0 files" or something like that? the code i am using is below, hopefully this will help some other people also.

@echo off
setlocal enabledelayedexpansion
for /l %%x in (1,1,1000) do (

    echo Taking ownsership of Folders & Files - loop %%x
    for /f "delims=" %%i in ('takeown.exe /R /A /F "F:\Shares\NetBackup Clients" /D N ^| findstr /i /C:"Failed processing 0 files"') do (
        set "error=%%i"
        if "!errorlevel!"=="0" goto :end
    )

    echo Applying permissions to filestore - loop %%x
    icacls.exe "F:\Shares\NetBackup Clients" /grant "Domain\Group":F /grant "Domain\Group":R /T /C

    echo Finished applying permissions to filestore - loop %%x >> C:\Loopy.txt
)
goto :eof
:end
echo %error% 

Many Thanks


Solution

  • I think you might have the error the wrong way around, so you would need to adjust it accordingly, but we use findstr and if we meet the requirement (errorlevel is 0) we exit the loop.

    @echo off
    setlocal enabledelayedexpansion
    for /l %%x in (1,1,1000) do (
        echo %%x
        for /f "delims=" %%i in ('takeown.exe /R /A /F "\\fileserver\share\" /D N ^| findstr /i "Failed processing 0 files"') do (
            set "error=%%i"
            if "!errorlevel!"=="0" goto :end
        )
        echo Finished takeown >> C:\Loopy.txt
        icacls.exe "\\fileserver\share\" /grant "Domain\Group":F /grant "Domain\Group":R /T /C
        echo Finished icacls >> C:\Loopy.txt
        echo Loop %%x >> C:\Loopy.txt
    )
    goto :eof
    :end
    echo %error%