0

I am trying to run this script as administrator. When I run it without admin rights the log file is save in C:\Windows\System32. I put echo %~dp0 in the script and it echos to the current directory.

%~dp0
SC QUERY | FINDSTR "Fax" 
IF ERRORLEVEL 0 SC CONFIG Fax START= DISABLED >> log.txt

If I hard set the log file as this:

%~dp0
SC QUERY | FINDSTR "Fax" 
IF ERRORLEVEL 0 SC CONFIG Fax START= DISABLED >> C:\logs\log.txt

I can get a log in that location. But I only need to run it on machines with issues and I would like to have the file on the USB.

NoNo
  • 123
  • 6

1 Answers1

1

Try the following code snippet:

@ECHO OFF
SETLOCAL EnableExtensions
SC QUERY state= all | FINDSTR "Fax"
REM alternatively: SC QUERY Fax | FINDSTR "Fax"
IF ERRORLEVEL 2 (
    REM Findstr: Wrong syntax
) else (
    IF ERRORLEVEL 1 (
        REM "Fax": A match not found  
    ) else (
        REM "Fax": A match is found in at least one line of the query
        >> "%~dp0log.txt" SC CONFIG Fax START= DISABLED
    )
)

Explanation:

  • note that SC QUERY without any option enumerates only running services (default state= active), see SC /?;
  • check IF ERRORLEVEL number in descending order as ERRORLEVEL number specifies a true condition if the last program run returned an exit code equal to or greater than the number specified (i.e. IF ERRORLEVEL 0 is always valid), see IF /?;
  • %~dp0 expands %0 to a drive letter and path (incl. trailing backslash), see call /?. Note that %~dp0 will return the Drive and Path to the batch script, see Links relative to the Batch Script)
  • >> "%~dp0log.txt" SC … - see redirection.
JosefZ
  • 1,564
  • 1
  • 10
  • 18