Corey Shelton
Corey Shelton

Reputation: 11

Change Directory of Batch File to the batch file's location

Weekly, I have to update our computers with publications for our aircraft. I have streamlined the process by creating a batch file that deletes the old publications automatically and opens the folder where they are stored so I don't have to dig for it. The location where the publications are stored each week is the same. My batch file looks like below...

del /s /f "C:\Users\Public\Desktop\PubFolder\Pub.pdf"

So basically all I have to do is copy the PubFolder from my USB drive to the Public Desktop after I have ran the batch file to delete all of the publications.

If all of our computers were exactly the same, this would be an easy fix because I could write in the batch file

xcopy /y D:\PubFolder" "C:\Users\Public\Desktop\PubFolder"

and the script would do all of the work for me. My issue is, a lot of the computers have different software installed on them which require partitions in the HDD. Some of them have 3, some 2, some 1.

Basically what I'm needing is when I run the batch file from the USB, it uses the location of the batch file as the directory so I can copy from there.

Upvotes: 1

Views: 111

Answers (2)

lit
lit

Reputation: 16226

A cmd script (.bat file) can reference its own directory with %~dp0

See the details using FOR /?

While you are at it, some additional error checking might make some situations easier to recover from.

SETLOCAL
SET "EXITCODE=0"

SET "USERDIR=%PUBLIC%\Desktop\PubFolder"

IF NOT EXIST "%USERDIR%" (
    ECHO ERROR: The user publication directory "%USERDIR%" does not exist.
    SET EXITCODE=4
    GOTO TheEnd
)

IF EXIST "%USERDIR%\Pub.pdf" (DEL "%USERDIR%\Pub.pdf")

xcopy /y %~dp0PubFolder" "%USERDIR%"
SET "EXITCODE=%ERRORLEVEL%"
IF %EXITCODE% NEQ 0 (
    ECHO ERROR: Failed to copy from "%~dp0" to "%USERDIR%"
    SET EXITCODE=5
    GOTO TheEnd
)

:TheEnd
EXIT /B %EXITCODE%

Upvotes: 1

jwdonahue
jwdonahue

Reputation: 6659

@setlocal
REM If you have pre-Vista machines, uncomment the folowing line:
REM @if not defined PUBLIC set PUBLIC=%SYSTEMDRIVE%\Users\Public%
@xcopy /y %~d0\PubFolder %PUBLIC%\Desktop\PubFolder

Upvotes: 0

Related Questions