FOR Loop set failing with values that have spaces

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

FOR Loop set failing with values that have spaces

#1 Post by SIMMS7400 » 21 Nov 2016 10:29

Hi Folks -

For some reason the below code is failing when it encounters a value with a space (i.e. "Hyperion RMI Registry"), even though it's quoted.

Code: Select all

echo ********************************************************
echo %ACTION:s=S% EPM Services on Reporting and Planning Server                              
echo ********************************************************

FOR %%S IN (
 "OracleProcessManager_ohsInstance4262192120"^
 "HyS9FoundationServices"^
 "HyS9RaFramework"^
 "HyS9RAFrameworkAgent"^
 "HyS9FRReports"^
 "HyS9FRPrint"^
 "HyS9WebAnalysis"^
 "Hyperion RMI Registry"^
 "HyS9Planning"
 ) DO (

CALL SafeStopStartRestart.cmd %ACTION% %%S %RPT_SRVR% %PLOGPATH% %PERRORPATH%

)


I've tried everything but can't get it to work. Anyone have any ideas?

Thanks

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: FOR Loop set failing with values that have spaces

#2 Post by aGerman » 21 Nov 2016 11:24

Does "everything" include omitting the carets (^)?

Steffen

Compo
Posts: 599
Joined: 21 Mar 2014 08:50

Re: FOR Loop set failing with values that have spaces

#3 Post by Compo » 21 Nov 2016 11:28

Not only are none of those carets needed, I'd suggest that your call command is being run correctly and your code is failing somewhere in the main routine when %2 or whatever takes its value removes the doublequotes when it shouldn't.

SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

Re: FOR Loop set failing with values that have spaces

#4 Post by SIMMS7400 » 21 Nov 2016 11:50

HI Folks -

Thanks for the reply!

It's failing before it even interacts with the main routine.

Once it encounters the set value with the quotes spaces, it fails there. I've removed the carrots but still fails.

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: FOR Loop set failing with values that have spaces

#5 Post by aGerman » 21 Nov 2016 12:01

How do the lines look like if you output them?

Code: Select all

ECHO CALL SafeStopStartRestart.cmd %ACTION% %%S %RPT_SRVR% %PLOGPATH% %PERRORPATH%

SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

Re: FOR Loop set failing with values that have spaces

#6 Post by SIMMS7400 » 21 Nov 2016 12:15

Hi Steffan -=

Here are the results of your previous question:

Code: Select all

SafeStopStartRestart.cmd stop "OracleProcessManager_ohsInstance4262192120" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\ 

SafeStopStartRestart.cmd stop "Hyperion RMI Registry" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9FoundationServices" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9FRPrint" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9FRReports" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9Planning" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9RAFrameworkAgent" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9RaFramework" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9WebAnalysis" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\


Everything looks perfectly fine.

Also, here is the main routine if you wanted to peruse that. As I said, it's not even making it to the main routine.

Code: Select all

::-- Set Working Directory as Script Path --::

cd /d %~dp0

::-- Call Environment File --::

call _env.cmd

::-- Set Main Intrapath Variables --::
::-- Set Process in variables below i.e. EPMA_Logs\

SET PLOGPATH=%4
SET PERRORPATH=%5

SET intrapath=%MAINPATH%%LOGPATH%%PLOGPATH%
SET errorintrapath=%MAINPATH%%ERRORPATH%%PERRORPATH%

IF NOT EXIST %intrapath%      MKDIR %intrapath%
IF NOT EXIST %errorintrapath% MKDIR %errorintrapath%

::-- Prepare Main Log and Error Files  --::

FOR /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set timestamp=%%a%%b)
FOR /f "tokens=* delims= " %%c in ("%timestamp%") do (set timestamp=%%c)

::-- Append server name to log ^& error files --::
IF %~2==Restart_Server (
   SET logfile=%intrapath%%1_%3_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
   SET errorfile=%errorintrapath%%1_%3_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
   GOTO 1
   )

::-- Append service name to log ^& error files --::
SET logfile=%intrapath%%1_%2_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
SET errorfile=%errorintrapath%%1_%2_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log

:1

IF EXIST %logfile% DEL %logfile%
IF EXIST %errorfile% DEL %errorfile%

::-- Call function to pass in ACTION ^| SERVICE ^| SERVER --::

CALL :EXEC_ACTION %1 %2 %3

::-- Return to main script to process more commands or exit session --::

EXIT /B

::::::::::::::::::::::::::::::
::-- Functions Below Here --::
::::::::::::::::::::::::::::::

:EXEC_ACTION

::-- Ensure command line argurement exist before processing --%
IF [%1] == [] GOTO Usage
IF [%2] == [] GOTO Usage
IF [%3] == [] GOTO Usage

::-- Set command line arguements to a variable for easier reading --::
::-- Perform variable transformation --::

SET ACTION=%~1
SET SERVICENAME=%2
SET SYSTEMNAME=%~3

ECHO %ACTION%
ECHO %SERVICENAME%
ECHO %SYSTEMNAME%
TIMEOUT /T 2

::-- Uppercase action values --::
SET "str=%ACTION%"
FOR /f "usebackq delims=" %%I IN (`powershell "\"%str%\".toUpper()"`) DO SET "ACTION=%%~I"

::-- Set Main Script Variables --::
SET STATE=
SET CURRENT_STATUS=
SET RSFLAG=

SET /A DEFAULT_DELAY=10
SET /A SLEEP_COUNT=0
SET /A RESTARTED=0
SET /A MAX_WAIT_PERIODS=5
SET /A PING_CNT=0

::-- Set Ping Delay based on Action --::
IF %~1==stop (
   SET /A PING_DELAY=10
   ) ELSE IF %~1==STOP (
      SET /A PING_DELAY=10
   ) ELSE IF %~1==restart_server (
      SET /A PING_DELAY=10
   ) ELSE (
      SET /A PING_DELAY=60
   )

::-- If Server related, set Server to NOT APPLICABLE --::
::-- Set RSFLAG==T so server processes only against relevant code --:
::-- Find IP Address and Set as Variable --::

IF %~2==Restart_Server (
   SET SERVICENAME=NOT_APPLICABLE
   SET RSFLAG=T
   FOR /f "delims=[] tokens=2" %%a IN ('ping %SYSTEMNAME% -n 1 ^| findstr "["') DO SET IP=%%a
   )


::-- Display content to CLI for manual execution --::
CLS
ECHO ************************************************************************
ECHO Process Info  : %TIME%                                                         
ECHO ------------------------------------------------------------------------                                                               
ECHO Server Name   : %SYSTEMNAME%
IF [%IP%] NEQ [] (
ECHO IP Address    : %IP%
)
ECHO.                                             
ECHO Action        : %ACTION%                                                 
ECHO Service Name  : %SERVICENAME:"=%                                   
ECHO.

IF [%RSFLAG%] == [] (
   ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME%
)   ELSE (                                                                       
      ECHO Attempting to %ACTION% : %SYSTEMNAME%
   )
   
ECHO ------------------------------------------------------------------------

::-- Delay execution based on Action --::
PING -n %PING_DELAY% 127.0.0.1>nul

ECHO ************************************************************************  >>%logfile%
ECHO Process Info  : %TIME%                                                    >>%logfile%
ECHO ------------------------------------------------------------------------  >>%logfile%                                                                 
ECHO Server Name   : %SYSTEMNAME%                                              >>%logfile%
IF [%IP%] NEQ [] (
ECHO IP Address    : %IP%                                          >>%logfile%
)
ECHO.                                                                          >>%logfile%
ECHO Action        : %ACTION%                                                  >>%logfile%
ECHO Service Name  : %SERVICENAME:"=%                                          >>%logfile%
ECHO.                                                                          >>%logfile%

IF [%RSFLAG%] == [] (
   ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME% >>%logfile%
)   ELSE (                                                                       
      ECHO Attempting to %ACTION% : %SYSTEMNAME%                             >>%logfile%
   )
ECHO ------------------------------------------------------------------------  >>%logfile%

::-- Ensure Service and^/or Server is valid, accessiable, and not offline --::

::-- If service related, skip over below code as it only pertains to servers --::
IF [%RSFLAG%] == [] GOTO SRVC

ping -n 1 %SYSTEMNAME% | FIND /i "TTL=" >nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                               >>%logfile%
   ECHO Server %SYSTEMNAME% is valid and available for processing >>%logfile%
   ECHO.                                              >>%logfile%
   GOTO RestartServer
   )

:P2
ping -n 1 %SYSTEMNAME% | FIND /i "Destination host unreachable" >nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                                           >>%logfile%
   ECHO %SYSTEMNAME% is unreachable ^: No valid route to the requested host   >>%logfile%
   ECHO Will try to contact host %MAX_WAIT_PERIODS% more times                >>%logfile%
   ECHO.                                                           >>%logfile%
      IF "%PING_CNT%"=="%MAX_WAIT_PERIODS%" (
       ECHO.                                                                  >>%logfile%
        ECHO %SYSTEMNAME% state won't change. Script exececution is canceled   >>%logfile%
      ECHO.                                                                  >>%logfile%
        GOTO EndExit
      )
   PING -n %DEFAULT_DELAY% 127.0.0.1>nul
   SET /A PING_CNT+=1
   GOTO P2
   )

:P3
ping -n 1 %SYSTEMNAME% | FIND /i "Request timed out" >nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                                              >>%logfile%
   ECHO The request to %SYSTEMNAME% has timed out                                >>%logfile%
   ECHO No ECHO reply messages were recieved within the default time of 1 second >>%logfile%
   ECHO.                                                              >>%logfile%
   ECHO Will try to contact host %MAX_WAIT_PERIODS% more times                   >>%logfile%
   ECHO.                                                              >>%logfile%
      IF "%PING_CNT%"=="%MAX_WAIT_PERIODS%" (
       ECHO.                                                                     >>%logfile%
        ECHO %SYSTEMNAME% state won't change. Script exececution is canceled      >>%logfile%
      ECHO.                                                                     >>%logfile%
        GOTO EndExit
      )
   PING -n %DEFAULT_DELAY% 127.0.0.1>nul
   SET /A PING_CNT+=1
   GOTO P3
   )

ping -n 1 %SYSTEMNAME% | FIND /i "could not find host">nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                                  >>%logfile%
   ECHO %SYSTEMNAME% is not valid : No further attempts will be made >>%logfile%
   ECHO.                                                  >>%logfile%
   GOTO EndExit
   )


:SRVC
%PSSERVICE% \\%3 query %SERVICENAME% | FIND "FAILED 1060" >nul 2>&1
IF %ERRORLEVEL%==0 (
    ECHO.                                             >>%logfile%
    ECHO Failure! Service %SERVICENAME% is not valid! >>%logfile%
   ECHO.                                             >>%logfile%
    GOTO EndExit
)
%PSSERVICE% \\%3 query %SERVICENAME% | FIND "STATE" >nul 2>&1
IF %ERRORLEVEL%==1 (
    ECHO.                                                                               >>%logfile%
    ECHO Failure! Server \\%3 or service %SERVICENAME% is not accessible or is offline! >>%logfile%
   ECHO.                                                                               >>%logfile%
    GOTO EndExit
)

:Dispatch

::-- Parse output of command and set STATE as a variable for script processing --::
FOR /f "tokens=4" %%S IN ('%PSSERVICE% \\%3 query %SERVICENAME% ^| FIND "STATE"') DO SET CURRENT_STATUS=%%S

ECHO Current State : Service is %CURRENT_STATUS% >>%logfile%

::-- Perform required checks and balances after service has been stopped or started --::
IF NOT "%CURRENT_STATUS%"=="RUNNING" IF NOT "%CURRENT_STATUS%"=="STOPPED" IF NOT "%CURRENT_STATUS%"=="PAUSED" (
    IF "%SLEEP_COUNT%"=="%MAX_WAIT_PERIODS%" (
       ECHO.                                                           >>%logfile%
        ECHO Service state won't change. Script exececution is canceled.>>%logfile%
      ECHO.                                                           >>%logfile%
        GOTO EndExit
    )
   ECHO.                                                               >>%logfile%
    ECHO Service State is changing, waiting %DEFAULT_DELAY% seconds...  >>%logfile%
   ECHO.                                                               >>%logfile%
    PING -n %DEFAULT_DELAY% 127.0.0.1>nul
   SET /A SLEEP_COUNT+=1
   GOTO Dispatch

)

IF %ACTION%==START (
    IF %CURRENT_STATUS%==RUNNING (
        ECHO.                                                  >>%logfile%
        ECHO Warning! Service %SERVICENAME% is already running >>%logfile%
      ECHO.                                                  >>%logfile%
        ECHO No further processing required                    >>%logfile%
        ECHO.                                                  >>%logfile%
        GOTO EndExit
    ) ELSE (
        GOTO StartService
    )
) ELSE IF %ACTION%==RESTART (
    IF %CURRENT_STATUS%==RUNNING (
        IF %RESTARTED%==1 (
         ECHO.                                                           >>%logfile%
         ECHO Warning! Service %SERVICENAME% has already been restarted  >>%logfile%
         ECHO.                                                           >>%logfile%
            ECHO No further processing required                             >>%logfile%
         ECHO.                                                           >>%logfile%
            GOTO EndExit
        )
        SET /A SLEEP_COUNT=0
        GOTO StopService
    ) ELSE (
        SET /A RESTARTED=1
        GOTO StartService
    )
) ELSE IF %ACTION%==STOP (
    IF %CURRENT_STATUS%==STOPPED  (
      ECHO.                                                           >>%logfile%
        ECHO Warning! Service %SERVICENAME% is already stopped.         >>%logfile%
      ECHO.                                                           >>%logfile%
      ECHO No further processing required                             >>%logfile%
      ECHO.                                                           >>%logfile%
        GOTO EndExit
    ) ELSE (
        GOTO StopService
    )
)

:StartService

::-- Ensure conlficts are captured and addressed appropriately --::
::-- For instance, a service could have a status of STOPPED and an action of START --::
::-- When SC or PsService goes to start it, it fails because infact it's already started --::

ECHO Starting %SERVICENAME% on \\%SYSTEMNAME%                  >>%logfile%

SET FND_STRNG=Error
%PSSERVICE% \\%3 start %SERVICENAME% |findstr /C:"%FND_STRNG%" >>%logfile%

IF %ERRORLEVEL%==0 (

   ECHO.                                                >>%logfile%
   ECHO Warning! A service conflicts exists:            >>%logfile%
   ECHO.                                                >>%logfile%
   ECHO %~2 returned a %CURRENT_STATUS% status          >>%logfile%
   ECHO The action was to %ACTION% the service          >>%logfile%
   ECHO PsService FAILED because it was already STARTED >>%logfile%
   ECHO.                                                >>%logfile%
   ECHO Please verify the incorrect status setting       >>%logfile%
   ECHO.                                                >>%logfile%
   GOTO EndExit
)
   
ECHO.                                     >>%logfile%
ECHO Verifying service has been started...>>%logfile%
ECHO.                                     >>%logfile%
SET SLEEP_COUNT=0
GOTO Dispatch
   
:StopService
ECHO.                                          >>%logfile%
ECHO Stopping %SERVICENAME% on \\%SYSTEMNAME%  >>%logfile%
%PSSERVICE% \\%3 stop %SERVICENAME%            >>%logfile%
ECHO.                                          >>%logfile%
ECHO Verifying service has been stopped...     >>%logfile%
ECHO.                                          >>%logfile%
SET SLEEP_COUNT=0
GOTO Dispatch


:RestartServer
ECHO Restarting %SYSTEMNAME% at %TIME%                            >>%logfile%
CALL %WINDIR%\system32\shutdown -m \\%3 -r -t 00 ||GOTO FAILED

ECHO.                                                             >>%logfile%
ECHO %SYSTEMNAME% is being restarted : Allow 5 minutes to restart >>%logfile%
ECHO.                                                             >>%logfile%
GOTO EndExit

:FAILED
ECHO.                                                        >>%logfile%
ECHO Warning! Access is denied : Server can not be restarted >>%logfile%
ECHO.                                                        >>%logfile%
ECHO Contact your System Administrator                      >>%logfile%
ECHO.                                                        >>%logfile%
GOTO EndExit   


:Usage

>>%logfile%(

ECHO.
ECHO Warning! EPM Services processing has been aborted
ECHO.
ECHO %1,%2, or %3 has been provided in an incorrect format
ECHO.
ECHO See usage below:
ECHO.
ECHO This script can start/stop/restart a local or remote service, waiting for the service to stop/start ^(if necessary^).
ECHO.
ECHO Usage:
ECHO ^*_EPM_Services.cmd ^<start^|stop^|restart^> ^<SERVICE^> ^[SYSTEM^]
ECHO.
)
GOTO EndExit


:EndExit
ECHO ************************************************************************>>%logfile%
ECHO ALERT : Server %3 is done being processed - Exiting Server              >>%logfile%
ECHO ------------------------------------------------------------------------>>%logfile%                                                                       
ECHO.
GOTO :EOF


Thank you!!

penpen
Expert
Posts: 1996
Joined: 23 Jun 2013 06:15
Location: Germany

Re: FOR Loop set failing with values that have spaces

#7 Post by penpen » 22 Nov 2016 02:49

SIMMS7400 wrote:

Code: Select all

SafeStopStartRestart.cmd stop "OracleProcessManager_ohsInstance4262192120" 
DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "Hyperion RMI Registry" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9FoundationServices" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9FRPrint" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9FRReports" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9Planning" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9RAFrameworkAgent" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9RaFramework" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\

SafeStopStartRestart.cmd stop "HyS9WebAnalysis" DIDRHYPRPT03VW EPM_Services_Logs\ EPM_Services_Errors\
I hold the bet, that you have added the line aGerman has suggested without removing the original one:
Please remove the other line, or use this example (which works error free):

Code: Select all

@echo off
setlocal enableDelayedExpansion
set "ACTION=stop"
set "RPT_SRVR=DIDRHYPRPT03VW"
set "PLOGPATH=EPM_Services_Logs\"
set "PERRORPATH=EPM_Services_Errors\"

echo ********************************************************
echo %ACTION:s=S% EPM Services on Reporting and Planning Server                             
echo ********************************************************

FOR %%S IN (
 "OracleProcessManager_ohsInstance4262192120"
 "HyS9FoundationServices"
 "HyS9RaFramework"
 "HyS9RAFrameworkAgent"
 "HyS9FRReports"
 "HyS9FRPrint"
 "HyS9WebAnalysis"
 "Hyperion RMI Registry"
 "HyS9Planning"
) DO (
   echo CALL SafeStopStartRestart.cmd %ACTION% %%S %RPT_SRVR% %PLOGPATH% %PERRORPATH%
)
endlocal


Sidenote: I assume Compo is right, and your scripts breaks on one of your "unquoted if lines" using %~2(within "SafeStopStartRestart.cmd"), e.g.:

Code: Select all

IF %~2==Restart_Server (

which results in:

Code: Select all

IF Hyperion RMI Registry==Restart_Server (

Better use doublequotes:

Code: Select all

IF "%~2"=="Restart_Server" (


penpen

SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

Re: FOR Loop set failing with values that have spaces

#8 Post by SIMMS7400 » 22 Nov 2016 02:52

So to add some color, this main routine worked fine two days ago. However since then, I've added the section to capture server checks, (i.e. ping etc). However, I still see now issues. The weird thing is, if I replace the spaces in the call script with #'s, and then replace the # with spaces in the main routine, the script completes fine.

I'll post the main routine that worked and then the current one. I'm having a hard time understandinf why the latter wont work with the quotes values with spaces:

MR that worked:

Code: Select all

::-- Set Working Directory as Script Path --::

cd /d %~dp0

::-- Call Environment File --::

call _env.cmd

::-- Set Main Intrapath Variables --::
::-- Set Process in variables below i.e. EPMA_Logs\

SET PLOGPATH=%4
SET PERRORPATH=%5

SET intrapath=%MAINPATH%%LOGPATH%%PLOGPATH%
SET errorintrapath=%MAINPATH%%ERRORPATH%%PERRORPATH%

IF NOT EXIST %intrapath%      MKDIR %intrapath%
IF NOT EXIST %errorintrapath% MKDIR %errorintrapath%

::-- Prepare Main Log and Error Files  --::

FOR /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set timestamp=%%a%%b)
FOR /f "tokens=* delims= " %%c in ("%timestamp%") do (set timestamp=%%c)

SET logfile=%intrapath%%1_%2_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
SET errorfile=%errorintrapath%%1_%2_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log

IF EXIST %logfile% DEL %logfile%
IF EXIST %errorfile% DEL %errorfile%

::-- Call function to pass in ACTION ^| SERVICE ^| SERVER --::

CALL :EXEC_ACTION %1 %2 %3

::-- Return to main script to process more commands or exit session --::

EXIT /B

::::::::::::::::::::::::::::::
::-- Functions Below Here --::
::::::::::::::::::::::::::::::

:EXEC_ACTION

::-- Ensure command line argurement exist before processing --%
IF [%1] == [] GOTO Usage
IF [%2] == [] GOTO Usage
IF [%3] == [] GOTO Usage

::-- Set command line arguements to variable for easier reading --::
SET ACTION=%~1
SET SERVICENAME=%2
SET SYSTEMNAME=%~3

::-- Uppercase action values --::
SET "str=%ACTION%"
FOR /f "usebackq delims=" %%I IN (`powershell "\"%str%\".toUpper()"`) DO SET "ACTION=%%~I"

::-- Set Main Script Variables --::
SET STATE=
SET CURRENT_STATUS=
SET /A DEFAULT_DELAY=10
SET /A SLEEP_COUNT=0
SET /A RESTARTED=0
SET /A MAX_WAIT_PERIODS=5

::-- Set Ping Delay based on Action --::
IF %~1==stop (
   SET /A PING_DELAY=10
   ) ELSE IF %~1==STOP (
      SET /A PING_DELAY=10
   ) ELSE (
      SET /A PING_DELAY=60
   )   
   
::-- Used to shorten command line --::

SET PSSERVICE=PsService.exe

::-- Display content to CLI for manual execution --::
CLS
ECHO ************************************************************************
ECHO Process Info  :                                                           
ECHO ------------------------------------------------------------------------                                                               
ECHO Server Name   : %SYSTEMNAME%                                             
ECHO Action        : %ACTION%                                                 
ECHO Service Name  : %SERVICENAME:"=%                                         
ECHO.                                                                         
ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME%
ECHO ------------------------------------------------------------------------

::-- Delay execution based on Action --:: 
PING -n %PING_DELAY% 127.0.0.1>nul

ECHO ************************************************************************  >>%logfile%
ECHO Process Info  : %TIME%                                                    >>%logfile%
ECHO ------------------------------------------------------------------------  >>%logfile%                                                                 
ECHO Server Name   : %SYSTEMNAME%                                              >>%logfile%
ECHO Action        : %ACTION%                                                  >>%logfile%
ECHO Service Name  : %SERVICENAME:"=%                                          >>%logfile%
ECHO.                                                                          >>%logfile%
ECHO Attempting to %ACTION% service %SERVICENAME% on computer %SYSTEMNAME%     >>%logfile%
ECHO.                                                                          >>%logfile%
ECHO ------------------------------------------------------------------------  >>%logfile%

::-- Ensure Service and^/or Server is valid, accessiable, and not offline --::
%PSSERVICE% \\%3 query %SERVICENAME% | FIND "FAILED 1060" >nul 2>&1
IF %ERRORLEVEL%==0 (
    ECHO.                                             >>%logfile%
    ECHO Failure! Service %SERVICENAME% is not valid! >>%logfile%
   ECHO.                                             >>%logfile%
    GOTO EndExit
)
%PSSERVICE% \\%3 query %SERVICENAME% | FIND "STATE" >nul 2>&1
IF %ERRORLEVEL%==1 (
    ECHO.                                                                               >>%logfile%
    ECHO Failure! Server \\%3 or service %SERVICENAME% is not accessible or is offline! >>%logfile%
   ECHO.                                                                               >>%logfile%
    GOTO EndExit
)

:Dispatch

::-- Parse output of command and set STATE as a variable for script processing --::
FOR /f "tokens=4" %%S IN ('%PSSERVICE% \\%3 query %SERVICENAME% ^| FIND "STATE"') DO SET CURRENT_STATUS=%%S

ECHO Current State : Service is %CURRENT_STATUS% >>%logfile%

::-- Perform required checks and balances after service has been stopped or started --::
IF NOT "%CURRENT_STATUS%"=="RUNNING" IF NOT "%CURRENT_STATUS%"=="STOPPED" IF NOT "%CURRENT_STATUS%"=="PAUSED" (
    IF "%SLEEP_COUNT%"=="%MAX_WAIT_PERIODS%" (
       ECHO.                                                           >>%logfile%
        ECHO Service state won't change. Script exececution is canceled.>>%logfile%
      ECHO.                                                           >>%logfile%
        GOTO EndExit
    )
   ECHO.                                                             >>%logfile%
    ECHO Service State is changing, waiting %DEFAULT_DELAY% seconds...>>%logfile%
   ECHO.                                                             >>%logfile%
    PING -n %DEFAULT_DELAY% 127.0.0.1>nul
   SET /A SLEEP_COUNT+=1
   GOTO Dispatch

)

IF %ACTION%==START (
    IF %CURRENT_STATUS%==RUNNING (
        ECHO.                                                  >>%logfile%
        ECHO Warning! Service %SERVICENAME% is already running >>%logfile%
      ECHO.                                                  >>%logfile%
        ECHO No further processing required                    >>%logfile%
        ECHO.                                                  >>%logfile%
        GOTO EndExit
    ) ELSE (
        GOTO StartService
    )
) ELSE IF %ACTION%==RESTART (
    IF %CURRENT_STATUS%==RUNNING (
        IF %RESTARTED%==1 (
         ECHO.                                                           >>%logfile%
         ECHO Warning! Service %SERVICENAME% has already been restarted  >>%logfile%
         ECHO.                                                           >>%logfile%
            ECHO No further processing required                             >>%logfile%
         ECHO.                                                           >>%logfile%
            GOTO EndExit
        )
        SET /A SLEEP_COUNT=0
        GOTO StopService
    ) ELSE (
        SET /A RESTARTED=1
        GOTO StartService
    )
) ELSE IF %ACTION%==STOP (
    IF %CURRENT_STATUS%==STOPPED  (
      ECHO.                                                           >>%logfile%
        ECHO Warning! Service %SERVICENAME% is already stopped.         >>%logfile%
      ECHO.                                                           >>%logfile%
      ECHO No further processing required                             >>%logfile%
      ECHO.                                                           >>%logfile%
        GOTO EndExit
    ) ELSE (
        GOTO StopService
    )
)

:StartService
::-- Ensure conlficts are captured and addressed appropriately --::
::-- For instance, a service could have a status of STOPPED and an action of START --::
::-- When SC or PsService goes to start it, it fails because infact it's already started --::

SET FND_STRNG=Error
%PSSERVICE% \\%3 start %SERVICENAME% |findstr /C:"%FND_STRNG%" >>%logfile%

IF %ERRORLEVEL%==0 (

   ECHO.                                                >>%logfile%
   ECHO Warning! A service conflicts exists:            >>%logfile%
   ECHO.                                                >>%logfile%
   ECHO %~2 returned a %CURRENT_STATUS% status          >>%logfile%
   ECHO The action was to %ACTION% the service          >>%logfile%
   ECHO PsService FAILED because it was already STARTED >>%logfile%
   ECHO.                                                >>%logfile%
   ECHO Please verify the incorrect status setting       >>%logfile%
   ECHO.                                                >>%logfile%
   GOTO EndExit
)
   
ECHO.                                     >>%logfile%
ECHO Verifying service has been started...>>%logfile%
ECHO.                                     >>%logfile%
SET SLEEP_COUNT=0
GOTO Dispatch
   
:StopService
ECHO.                                          >>%logfile%
ECHO Stopping %SERVICENAME% on \\%SYSTEMNAME%  >>%logfile%
%PSSERVICE% \\%3 stop %SERVICENAME%            >>%logfile%
ECHO.                                          >>%logfile%
ECHO Verifying service has been stopped...     >>%logfile%
ECHO.                                          >>%logfile%
SET SLEEP_COUNT=0
GOTO Dispatch

:Usage

>>%logfile%(

ECHO.
ECHO Warning! EPM Services processing has been aborted
ECHO.
ECHO %1,%2, or %3 has been provided in an incorrect format
ECHO.
ECHO See usage below:
ECHO.
ECHO This script can start/stop/restart a local or remote service, waiting for the service to stop/start ^(if necessary^).
ECHO.
ECHO Usage:
ECHO ^*_EPM_Services.cmd ^<start^|stop^|restart^> ^<SERVICE^> ^[SYSTEM^]
ECHO.
)
GOTO EndExit


:EndExit
ECHO ************************************************************************>>%logfile%
ECHO ALERT : Server %3 is done being processed - Exiting Server              >>%logfile%
ECHO ------------------------------------------------------------------------>>%logfile%                                                                       
ECHO.
GOTO :EOF


Latest MR that doesn't work:

Code: Select all

::-- Set Working Directory as Script Path --::

cd /d %~dp0

::-- Call Environment File --::

call _env.cmd

::-- Set Main Intrapath Variables --::
::-- Set Process in variables below i.e. EPMA_Logs\

SET PLOGPATH=%4
SET PERRORPATH=%5

SET intrapath=%MAINPATH%%LOGPATH%%PLOGPATH%
SET errorintrapath=%MAINPATH%%ERRORPATH%%PERRORPATH%

IF NOT EXIST %intrapath%      MKDIR %intrapath%
IF NOT EXIST %errorintrapath% MKDIR %errorintrapath%

::-- Prepare Main Log and Error Files  --::

FOR /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set timestamp=%%a%%b)
FOR /f "tokens=* delims= " %%c in ("%timestamp%") do (set timestamp=%%c)

::-- Append Server Name to Log ^& Error Files --::
IF %~2==Restart_Server (
   SET logfile=%intrapath%%1_%3_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
   SET errorfile=%errorintrapath%%1_%3_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
   GOTO 1
   )

::-- Append Service Name to Log ^& Error Files --::
SET logfile=%intrapath%%1_%2_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
SET errorfile=%errorintrapath%%1_%2_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log

:1

IF EXIST %logfile% DEL %logfile%
IF EXIST %errorfile% DEL %errorfile%

::-- Call function to pass in ACTION ^| SERVICE ^| SERVER --::

CALL :EXEC_ACTION %1 %2 %3

::-- Return to main script to process more commands or exit session --::

EXIT /B

::::::::::::::::::::::::::::::::::::::::::::::::::
::-- F U N C T I O N S    B E l O W   H E R E --::
::::::::::::::::::::::::::::::::::::::::::::::::::

:EXEC_ACTION
SET PSSERVICE=PsService.exe
::-- Ensure command line argurement exist before processing --::
IF [%1] == [] GOTO Usage
IF [%2] == [] GOTO Usage
IF [%3] == [] GOTO Usage

::-- Set command line arguements to a variable for easier reading --::
::-- Perform variable transformation --::

SET ACTION=%~1
SET SERVICENAME=%2
SET SYSTEMNAME=%~3

::-- Uppercase action values --::
SET "str=%ACTION%"
FOR /f "usebackq delims=" %%I IN (`powershell "\"%str%\".toUpper()"`) DO SET "ACTION=%%~I"

::-- Set Main Script Variables --::
SET STATE=
SET CURRENT_STATUS=
SET RSFLAG=

SET /A DEFAULT_DELAY=10
SET /A SLEEP_COUNT=0
SET /A RESTARTED=0
SET /A MAX_WAIT_PERIODS=5
SET /A PING_CNT=0

::-- Set Ping Delay based on Action --::
IF %~1==stop (
   SET /A PING_DELAY=10
   ) ELSE IF %~1==STOP (
      SET /A PING_DELAY=10
   ) ELSE IF %~1==restart_server (
      SET /A PING_DELAY=10
   ) ELSE (
      SET /A PING_DELAY=60
   )

::-- If Server related, set Server to NOT APPLICABLE --::
::-- Set RSFLAG==T so server processes only against relevant code --:
::-- Find IP Address and Set as Variable --::

IF %~2==Restart_Server (
   SET SERVICENAME=NOT_APPLICABLE
   SET RSFLAG=T
   FOR /f "delims=[] tokens=2" %%a IN ('ping %SYSTEMNAME% -n 1 ^| findstr "["') DO SET IP=%%a
   )

::-- Display content to CLI for manual execution --::
CLS
ECHO ************************************************************************
ECHO Process Info  : %TIME%                                                         
ECHO ------------------------------------------------------------------------                                                               
ECHO Server Name   : %SYSTEMNAME%
IF [%IP%] NEQ [] (
ECHO IP Address    : %IP%
)
ECHO.                                             
ECHO Action        : %ACTION%                                                 
ECHO Service Name  : %SERVICENAME:"=%                                   
ECHO.

IF [%RSFLAG%] == [] (
   ECHO Attempting to %ACTION% service %SERVICENAME:#= % on computer %SYSTEMNAME%
)   ELSE (                                                                       
      ECHO Attempting to %ACTION% : %SYSTEMNAME%
   )
   
ECHO ------------------------------------------------------------------------

::-- Delay execution based on Action --::
PING -n %PING_DELAY% 127.0.0.1>nul

ECHO ************************************************************************  >>%logfile%
ECHO Process Info  : %TIME%                                                    >>%logfile%
ECHO ------------------------------------------------------------------------  >>%logfile%                                                                 
ECHO Server Name   : %SYSTEMNAME%                                              >>%logfile%
IF [%IP%] NEQ [] (
ECHO IP Address    : %IP%                                          >>%logfile%
)
ECHO.                                                                          >>%logfile%
ECHO Action        : %ACTION%                                                  >>%logfile%
ECHO Service Name  : %SERVICENAME:"=%                                          >>%logfile%
ECHO.                                                                          >>%logfile%

IF [%RSFLAG%] == [] (
   ECHO Attempting to %ACTION% service %SERVICENAME:#= % on computer %SYSTEMNAME% >>%logfile%
)   ELSE (                                                                       
      ECHO Attempting to %ACTION% : %SYSTEMNAME%                                 >>%logfile%
   )
ECHO ------------------------------------------------------------------------      >>%logfile%

::-- If service related, skip over below code as it only pertains to servers --::
IF [%RSFLAG%] == [] GOTO SRVC

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::-- B E G I N   S E R V E R   R E L A T E D   S E C T I O N   O N L Y --::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

::-- Ensure Server is valid, accessible, and not offline --::
::-- Else do no execute specified action --::

ping -n 1 %SYSTEMNAME% | FIND /i "TTL=" >nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                               >>%logfile%
   ECHO Server %SYSTEMNAME% is valid and available for processing >>%logfile%
   ECHO.                                              >>%logfile%
   GOTO RestartServer
   )

:P2
ping -n 1 %SYSTEMNAME% | FIND /i "Destination host unreachable" >nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                                           >>%logfile%
   ECHO %SYSTEMNAME% is unreachable ^: No valid route to the requested host   >>%logfile%
   ECHO Will try to contact host %MAX_WAIT_PERIODS% more times                >>%logfile%
   ECHO.                                                           >>%logfile%
      IF "%PING_CNT%"=="%MAX_WAIT_PERIODS%" (
       ECHO.                                                                  >>%logfile%
        ECHO %SYSTEMNAME% state won't change. Script exececution is canceled   >>%logfile%
      ECHO.                                                                  >>%logfile%
        GOTO EndExit
      )
   PING -n %DEFAULT_DELAY% 127.0.0.1>nul
   SET /A PING_CNT+=1
   GOTO P2
   )

:P3
ping -n 1 %SYSTEMNAME% | FIND /i "Request timed out" >nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                                              >>%logfile%
   ECHO The request to %SYSTEMNAME% has timed out                                >>%logfile%
   ECHO No ECHO reply messages were recieved within the default time of 1 second >>%logfile%
   ECHO.                                                        >>%logfile%
   ECHO This error is most likely due to a routing error or silent discard        >>%logfile%
   ECHO.                                                              >>%logfile%
   ECHO Will try to contact host %MAX_WAIT_PERIODS% more times                   >>%logfile%
   ECHO.                                                              >>%logfile%
      IF "%PING_CNT%"=="%MAX_WAIT_PERIODS%" (
       ECHO.                                                                     >>%logfile%
        ECHO %SYSTEMNAME% state won't change. Script exececution is canceled      >>%logfile%
      ECHO.                                                                     >>%logfile%
        GOTO EndExit
      )
   PING -n %DEFAULT_DELAY% 127.0.0.1>nul
   SET /A PING_CNT+=1
   GOTO P3
   )

ping -n 1 %SYSTEMNAME% | FIND /i "could not find host">nul 2>&1

IF %ERRORLEVEL%==0 (
   ECHO.                                                  >>%logfile%
   ECHO %SYSTEMNAME% is not valid : No further attempts will be made >>%logfile%
   ECHO.                                                  >>%logfile%
   GOTO EndExit
   )

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
::-- E N D   S E R V E R   R E L A T E D   S E C T I O N   O N L Y --::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

::-- Ensure Service is valid, accessible, and not offline --::
::-- Else do no execute specified action --::

:SRVC
%PSSERVICE% \\%3 query %SERVICENAME:#= % | FIND "FAILED 1060" >nul 2>&1
IF %ERRORLEVEL%==0 (
    ECHO.                                                 >>%logfile%
    ECHO Failure! Service %SERVICENAME:#= % is not valid! >>%logfile%
   ECHO.                                                 >>%logfile%
    GOTO EndExit
)
%PSSERVICE% \\%3 query %SERVICENAME:#= % | FIND "STATE" >nul 2>&1
IF %ERRORLEVEL%==1 (
    ECHO.                                                                                   >>%logfile%
    ECHO Failure! Server \\%3 or service %SERVICENAME:#= % is not accessible or is offline! >>%logfile%
   ECHO.                                                                                   >>%logfile%
    GOTO EndExit
)

:Dispatch

::-- Parse output of command and set STATE as a variable for script processing --::
FOR /f "tokens=4" %%S IN ('%PSSERVICE% \\%3 query %SERVICENAME:#= % ^| FIND "STATE"') DO SET CURRENT_STATUS=%%S

ECHO Current State : Service is %CURRENT_STATUS% >>%logfile%

::-- Perform required checks and balances after service has been stopped or started --::
IF NOT "%CURRENT_STATUS%"=="RUNNING" IF NOT "%CURRENT_STATUS%"=="STOPPED" IF NOT "%CURRENT_STATUS%"=="PAUSED" (
    IF "%SLEEP_COUNT%"=="%MAX_WAIT_PERIODS%" (
       ECHO.                                                           >>%logfile%
        ECHO Service state won't change. Script exececution is canceled.>>%logfile%
      ECHO.                                                           >>%logfile%
        GOTO EndExit
    )
   ECHO.                                                               >>%logfile%
    ECHO Service State is changing, waiting %DEFAULT_DELAY% seconds...  >>%logfile%
   ECHO.                                                               >>%logfile%
    PING -n %DEFAULT_DELAY% 127.0.0.1>nul
   SET /A SLEEP_COUNT+=1
   GOTO Dispatch

)

IF %ACTION%==START (
    IF %CURRENT_STATUS%==RUNNING (
        ECHO.                                                  >>%logfile%
        ECHO Warning! Service %SERVICENAME:#= % is already running >>%logfile%
      ECHO.                                                  >>%logfile%
        ECHO No further processing required                    >>%logfile%
        ECHO.                                                  >>%logfile%
        GOTO EndExit
    ) ELSE (
        GOTO StartService
    )
) ELSE IF %ACTION%==RESTART (
    IF %CURRENT_STATUS%==RUNNING (
        IF %RESTARTED%==1 (
         ECHO.                                                               >>%logfile%
         ECHO Warning! Service %SERVICENAME:#= % has already been restarted  >>%logfile%
         ECHO.                                                               >>%logfile%
            ECHO No further processing required                                 >>%logfile%
         ECHO.                                                               >>%logfile%
            GOTO EndExit
        )
        SET /A SLEEP_COUNT=0
        GOTO StopService
    ) ELSE (
        SET /A RESTARTED=1
        GOTO StartService
    )
) ELSE IF %ACTION%==STOP (
    IF %CURRENT_STATUS%==STOPPED  (
      ECHO.                                                           >>%logfile%
        ECHO Warning! Service %SERVICENAME:#= % is already stopped.     >>%logfile%
      ECHO.                                                           >>%logfile%
      ECHO No further processing required                             >>%logfile%
      ECHO.                                                           >>%logfile%
        GOTO EndExit
    ) ELSE (
        GOTO StopService
    )
)

:StartService
::-- Ensure conlficts are captured and addressed appropriately --::
::-- For instance, a service could have a status of STOPPED and an action of START --::
::-- However the service may actually be started as PsService or SC will failed --::

ECHO Starting %SERVICENAME:#= % on \\%SYSTEMNAME%                  >>%logfile%

SET FND_STRNG=Error
%PSSERVICE% \\%3 start %SERVICENAME:#= % |findstr /C:"%FND_STRNG%" >>%logfile%

IF %ERRORLEVEL%==0 (

   ECHO.                                                >>%logfile%
   ECHO Warning! A service conflicts exists:            >>%logfile%
   ECHO.                                                >>%logfile%
   ECHO %~2 returned a %CURRENT_STATUS% status          >>%logfile%
   ECHO The action was to %ACTION% the service          >>%logfile%
   ECHO PsService FAILED because it was already STARTED >>%logfile%
   ECHO.                                                >>%logfile%
   ECHO Please verify the incorrect status setting       >>%logfile%
   ECHO.                                                >>%logfile%
   GOTO EndExit
)
   
ECHO.                                     >>%logfile%
ECHO Verifying service has been started...>>%logfile%
ECHO.                                     >>%logfile%
SET SLEEP_COUNT=0
GOTO Dispatch
   
:StopService
ECHO.                                              >>%logfile%
ECHO Stopping %SERVICENAME:#= % on \\%SYSTEMNAME%  >>%logfile%
%PSSERVICE% \\%3 stop %SERVICENAME:#= %            >>%logfile%
ECHO.                                              >>%logfile%
ECHO Verifying service has been stopped...         >>%logfile%
ECHO.                                              >>%logfile%
SET SLEEP_COUNT=0
GOTO Dispatch

:RestartServer
ECHO Restarting %SYSTEMNAME% at %TIME%                            >>%logfile%
CALL %WINDIR%\system32\shutdown -m \\%3 -r -t 00 ||GOTO FAILED

ECHO.                                                             >>%logfile%
ECHO %SYSTEMNAME% is being restarted : Allow 5 minutes to restart >>%logfile%
ECHO.                                                             >>%logfile%
GOTO EndExit

:FAILED
ECHO.                                                        >>%logfile%
ECHO Warning! Access is denied : Server can not be restarted >>%logfile%
ECHO.                                                        >>%logfile%
ECHO Contact your System Administrator                      >>%logfile%
ECHO.                                                        >>%logfile%
GOTO EndExit   


:Usage

>>%logfile%(

ECHO.
ECHO Warning! EPM Services processing has been aborted
ECHO.
ECHO %1,%2, or %3 has been provided in an incorrect format
ECHO.
ECHO See usage below:
ECHO.
ECHO This script can start/stop/restart a local or remote service, waiting for the service to stop/start ^(if necessary^).
ECHO.
ECHO Usage:
ECHO SafeStopStartRestart.cmd ^<start^|stop^|restart^> ^<SERVICE^> ^[SYSTEM^]
ECHO.
)
GOTO EndExit

:EndExit
ECHO ************************************************************************>>%logfile%
ECHO ALERT : Server %3 is done being processed - Exiting Server              >>%logfile%
ECHO ------------------------------------------------------------------------>>%logfile%                                                                       
ECHO.
GOTO :EOF



Thanks!

SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

Re: FOR Loop set failing with values that have spaces

#9 Post by SIMMS7400 » 22 Nov 2016 03:00

I found the issue:

I needed to quote Restart_Server" in the following blocks of code:

Code: Select all

::-- Append Server Name to Log ^& Error Files --::
IF %2=="Restart_Server" (
   SET logfile=%intrapath%%1_%3_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
   SET errorfile=%errorintrapath%%1_%3_%date:~-4,4%%date:~-10,2%%date:~-7,2%.log
   GOTO 1
   )


Code: Select all

::-- If Server related, set Server to NOT APPLICABLE --::
::-- Set RSFLAG==T so server processes only against relevant code --:
::-- Find IP Address and Set as Variable --::

IF %2=="Restart_Server" (
   SET SERVICENAME=NOT_APPLICABLE
   SET RSFLAG=T
   FOR /f "delims=[] tokens=2" %%a IN ('ping %SYSTEMNAME% -n 1 ^| findstr "["') DO SET IP=%%a
   )


Why though? How come stripping the quotes like %~2 didn't work?

penpen
Expert
Posts: 1996
Joined: 23 Jun 2013 06:15
Location: Germany

Re: FOR Loop set failing with values that have spaces

#10 Post by penpen » 22 Nov 2016 03:24

Because such lines don't match the syntax of the if statement:

Code: Select all

if a b == a b echo a b


The first comparand (here: "a") ends at the first special character such as whitespaces (here: " ").
Then the if statement expects a comparator, but "b" isn't one.

You have to fix it by making the special character behave like a normal one.
(The easiest one is to use doublequotes.)

But you could also do this:

Code: Select all

if a^ b == a^ b echo a b
setlocal enabledelayedExpansion
set "test=a b"
if !test! == !test! echo a b
endlocal
for %%a in ("a b") do if %%~a == %%~a echo ok


penpen

SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

Re: FOR Loop set failing with values that have spaces

#11 Post by SIMMS7400 » 22 Nov 2016 12:52

Pen Pen -

Thank you very much for the explanation. it makes perfect sense now.

I've adjusted my routine.

Thanks!

Squashman
Expert
Posts: 4471
Joined: 23 Dec 2011 13:59

Re: FOR Loop set failing with values that have spaces

#12 Post by Squashman » 22 Nov 2016 13:46

My best practice is to code it like this:

Code: Select all

IF "%~2"=="Restart_Server"


Then you know for sure you are comparing strings equally. You can't guarantee that the user passed in the command line argument with quotes. So strip the quotes if there are any and then just put them back on.

SIMMS7400
Posts: 544
Joined: 07 Jan 2016 07:47

Re: FOR Loop set failing with values that have spaces

#13 Post by SIMMS7400 » 26 Nov 2016 02:46

Thank you, Squash. I';ve updated my code accordingly.

Thanks!

Post Reply