#1 14 Oct 2017 05:48

MdKamil
Member
Registered: 14 Oct 2017
Posts: 2

Proper way to skip the loop and return from the function

Hi , i have written a batch script to check for service status and and based upon the result, some actions will be triggered . My doubt is it the proper way of skipping loop and the function getService. I knew that a inner for loop can be skipped by calling a separate function, but just wanted to confirm , is it a right approach ?

@echo off
set _param=%1

SETLOCAL EnableDelayedExpansion

if /i "%_param%" == "register" (
      call :getServiceStatus
      echo Service Status: !_status!
      rem // follow up ....
)
ENDLOCAL
goto:eof

:getServiceStatus
SETLOCAL EnableDelayedExpansion
set _commd_output=sc query %_app_name%
set _service_status=
FOR /f "tokens=*" %%H IN ('%_commd_output%') DO (
    IF "%%H" == "The specified service does not exist as an installed service." (
        set _service_status=UNINSTALLED
        goto skiploop
    ) ELSE (
        set _stmt=%%H
        IF /I "!_stmt:STATE=Found!" NEQ "!_stmt!" (
            FOR /f "tokens=3 delims=: " %%Q IN ("!_stmt!") DO (
                set _service_status=%%Q
                goto skiploop
            )
        )
    )
)
:skiploop
ENDLOCAL & set _status=%_service_status%
EXIT /B

Offline

#2 20 Oct 2017 13:07

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,059

Re: Proper way to skip the loop and return from the function

There is no "proper" way to break out of a "for" loop prematurely, but there are some workarounds.  You've done one of them.

Another would be to to replace your "goto skiploop" with "exit /b & set _status=!_service_status!"

The third one I can think of isn't really about breaking out early, rather you just wait out the loop with a null action if a condition is met.  This is not a great idea as it somewhat relies on you having a small data set (in your example this wouldn't be a big issue).

Side stepping the question a little, you can avoid the problem in your example by pre-filtering the output of "sc" with "find" or "findstr" to grab only the lines you want ("STATE", I'm assuming) and then you'll only get one line of output and thus no need to break the loop.


cmd | *sh | Ruby | Chef | Puppet | PowerShell | AutoIT3

Offline

#3 30 Oct 2017 13:04

MdKamil
Member
Registered: 14 Oct 2017
Posts: 2

Re: Proper way to skip the loop and return from the function

@bluesxman .. Thanks for your response and also mentioning other ways in which it can be performed.

Offline

Board footer

Powered by FluxBB