Praveen
Praveen

Reputation: 71

Filter specific Strings in For loop using batch Script

Directory structure C:Test\client1,C:\Test\client2....

Here I need to execute _Test.cmd files at time for specific clients only.

Please let me know how to filter the client names in this for loop using Batch script?

@Echo Off
setlocal enableDelayedExpansion
for /r C:\Install %%x in ("*_Test.cmd") do (
 ECHO [ !DATE! !TIME! ] Executing %%x ...
 CD %%~dx%%~px
 CALL _Test.cmd
 IF ERRORLEVEL 0 (
  ECHO [ !DATE! !TIME! ] Successful!
 )
)

Upvotes: 0

Views: 329

Answers (1)

Magoo
Magoo

Reputation: 80033

No idea how to distinguish "client name" from "not a client name".

If you mean "directory names" where each client has a directory, then:

@Echo Off
setlocal enableDelayedExpansion
pushd
for /d /r C:\test %%x in (.) do (
 ECHO [ !DATE! !TIME! ] Executing %%x ...
 CD %%~dpx
 CALL _Test.cmd
 IF NOT ERRORLEVEL 1 (
  ECHO [ !DATE! !TIME! ] Successful!
 )
)
popd

Notes: pushd/popd bracket saves the current directory and restores after for loop.

for /d /r means directories, recursive

Target "." means "all" - if you have a mask to apply, put that mask here.

cd %%~dpx is simply shorter than your version.

if errorlevel 0 is always true under normal circumstances. if errorlevel n means "if errorlevel is n or greater than n". cmd can be forced to set errorlevel negative, but it's a contrived situation.


" i need to run _Test.cmd for only particular clients like client24,client15,client40."

Now if you'd said that to start off with....

@Echo Off
setlocal enabledelayedexpansion
pushd
for /f "delims=" %%x in (yourfileofclients.txt) do if exist "c:\test\%%~x\." (
 ECHO [ !DATE! !TIME! ] Executing %%x ...
 CD "c:\test\%%~x"
 CALL _Test.cmd
 IF NOT ERRORLEVEL 1 (
  ECHO [ !DATE! !TIME! ] Successful!
 )
)
popd

Upvotes: 1

Related Questions