0

I want to create a .bat file to do the following things in the following order:

1) Get the directory path of a service

2) copy all files from that directory (files only) to a subfolder named "save"

The Service name exists and if I run "wmic service where "name='SERVICENAME'" get PathName" I get the Path, but for some reason the .bat files does not work as expected.

So far I have:

@echo off
setlocal
:PROMPT
SET /P UPDATESERVICE=Update Service (Y/[N])?
IF /I "%UPDATESERVICE%" NEQ "Y" GOTO END

FOR /F "tokens=*" %%g IN ('wmic service where "name='SERVICENAME'" get PathName') do (SET SERVICEPATH=%%g)

FOR %%a IN ("%SERVICEPATH%") DO FOR %%b IN ("%%~dpa.") SERVICEPATH=%%~dpb&%%~nxb
if not exist "%SERVICEPATH%\Save\" mkdir %SERVICEPATH%\Save
echo f | xcopy %SERVICEPATH%* %SERVICEPATH%\Save* /L /R 

:END
endlocal

This script should get the directory path of the service and copy all file from it and put them to a subfolder called "save". The idea is to make a backup of the existing files in the subdirectory and copy the new files over.

Jsn
  • 73
  • 10
  • so what is the question? What problems are you experiencing? – Gerhard Jan 15 '19 at 12:17
  • It just does not do the job and I dnt see why. If I echo the %SERVICEPATH% I do not get anything. When I run the .bat file, I get an error that the SERVICEPATH was unexpected at this time. – Jsn Jan 15 '19 at 12:20
  • 1
    Your 2nd nested for command has the `Do` keyword missing and also the `Set`. If the `&` in that line is meant to be part of the `set` you'll need to double quote - otherwise if the `&` concatenates another command the sole `%%~nxb` most likely is invalid. –  Jan 15 '19 at 12:31

1 Answers1

0

I got it working with this

@echo off

setlocal

:PROMPT

SET /P UPDATESERVICE=Update Service (Y/[N])?
IF /I "%UPDATESERVICE%" NEQ "Y" GOTO END

FOR /F "tokens=*" %%g IN ('wmic service where "name='MyServiceName'" get PathName') do (SET SERVICEPATH=%%g)

FOR %%a IN ("%SERVICEPATH%") DO FOR %%b IN ("%%~dpa.") do SERVICEPATH=%%~dpb&%%~nxb

if not exist "%SERVICEPATH%\Save\" mkdir %SERVICEPATH%\Save

echo f | xcopy /f /y %SERVICEPATH%* %SERVICEPATH%\Save*

:END

endlocal
Jsn
  • 73
  • 10
  • 1
    I recommend replacing the line `SET /P UPDATESERVICE=Update Service (Y/[N])?` by `%SystemRoot%\System32\choice.exe /C YN /N /M "Update Service (Y/[N])? "` and the line `IF /I "%UPDATESERVICE%" NEQ "Y" GOTO END` by `IF ERRORLEVEL 2 GOTO END`. Why this should be done is explained in detail in answer on [How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?](https://stackoverflow.com/a/49834019/3074564) It would be also better to use `"delims="` instead of `"tokens=*`. – Mofi Jan 15 '19 at 18:12