Search code examples
batch-fileif-statementconditional-statementserrorlevel

Batch File with two conditions and a loop


Let us assume my only method of scripting is via a batch file.

I have a batch file with a long list of commands, however, I need to include two contingencies:

  • Needs to be on the domain (we'll use .com for this example)
  • Must have a non typical IP (meaning 192 is not used on the domain, but is used prior to joining and not 169 due to delay in DHCP assignment).

I'd prefer to keep this in the same batch file as the rest of the code. I've tried sewing together some commands, but usually get a syntax error. I am able to make the IP portion work, using %ERRORLEVEL% however, I can only figure out searching for a single IP mask.

Here is a VERY wrong and rudimentary code:

    @ECHO off

    for /F "tokens=1*" %%G in ('SYSTEMINFO ^| FIND /I "DOMAIN:"') do (
        IF %%G == ".com" (
            GOTO :IPCheck
        ) ELSE ( GOTO :NoRun

    :IPCheck
    ipconfig | find /i "192." "169."
        if %ERRORLEVEL% == 0 goto IPCheck


     REM Domain address is configured and will continue script.)
    pause
    )

Solution

  • find isn't able to look for more than one search string. Findstr is. See findstr /? for more information.

    You don't even need any sort of loop:

    @echo off
    ipconfig | find "IPv4" | findstr /c:" 192." /c:" 169." >nul && goto :NoRun    
    systeminfo | findstr /RBE "Domain:.*\.com" >nul || goto :NoRun
    echo all ok. Insert payload here...
    goto :eof
    :NoRun
    echo this system doesn't meet the prerequisites.