6

Hi I'm fairly new to batch files, so sorry if this question seems stupid but I really need some help.

So I need my batch script to check if it is in a specified folder, say %userprofile%\Desktop for example. I don't want it to care about its own filename. I have absolutely no idea where to start. I know how to get the current path/filename etc but that's about all I know. How do I make the program compare its current path with the path that I want to see if it's in? Or is there another more efficient method?

What I want to achieve is like this:

if this file is in Desktop folder(
    echo It's here
)else(
    echo It's not here
)

Any help is appreciated, thanks everyone

2 Answers2

3

No need to apologize as the question you raised is more tricky than you probably expect.

Solution

This is how you can test that your batch file is located in a specific folder, in your case in Desktop folder:

@echo off

:: Normalize this batch script's path
set BATCH_PATH=%~dp0
set BATCH_PATH=%BATCH_PATH:~0,-1%

:: Test for equality
if "%BATCH_PATH%"=="%USERPROFILE%\Desktop" (
    echo This file is on Desktop.
) else (
    echo This file is not on Desktop.
)

Things to note

  • alternative way to normalize path (and my favorite) is:

    pushd "%~dp0"
    set BATCH_PATH=%CD%
    popd
    
    • in any case, you probably want to remove any trailing \, which is one of the things the normalization does for you
  • use %~dp0 variable instead of %cd%, because the latter semantics is the folder your scripts operates on while the first is the folder your script is located in (which is what you asked for)

    • %0 gives you your batch script location
    • by adding dp (i.e. %dp0) you ask for disk and path which omits the filename and extension (which is something like example.bat and it would be burden in next step - equality check)
    • by adding ~ you ask to remove any opening or closing " if necessary (i.e. the path contained space)
  • paths are wrapped in " to prevent errors due to possible space in the path string


Not as simple as one would thought, right?

0

Minimal working example using %cd%:

IF %cd%==%userprofile%\Desktop (
    ECHO It's here
) ELSE (
    ECHO It's not here
)

Using intermediate variable:

FOR /F "tokens=*" %%a in ('cd') do SET CURRENT_DIR=%%a
IF %CURRENT_DIR%==%userprofile%\Desktop (
    ECHO It's here
) ELSE (
    ECHO It's not here
)

Since you said you have no idea where to start, here is a good reading material: https://en.wikibooks.org/wiki/Windows_Batch_Scripting

Art Gertner
  • 7,429