Set environment variable and validate path

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
zickedi
Posts: 2
Joined: 06 Sep 2013 15:12

Set environment variable and validate path

#1 Post by zickedi » 06 Sep 2013 15:27

I have a function that sets an environment variable and in the end it should validate if the newly created environment variable links to an existing path. The part with the "if not exist" is not working. I tried various tipps with <setlocal>, <call set "var=%~1"> and so on, but nothing worked for me. Anyone can help?

##
CALL :FUNC_SET_VARIABLE VAR "C:\temp"

:FUNC_SET_VARIABLE
REM Function: Sets environment variable to value and validates it.
REM Example: CALL :FUNC_SET_VARIABLE [in/out] <variable> [in] <value>
if not defined %1 (
REM Variable is not set, so we do this now.
if "%~2"=="" (
set %1 & pause
exit 1
)
REM Set environment variable to value.
set %1=%~2
) else (
REM Variable is already set, so do nothing for now.
echo Variable already set.
)

if not exist "%~1" (
rem Environment variable links to invalid path:
echo # PATH-ERROR #
set %1 & pause
exit 1
)
goto :EOF
##

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

Re: Set environment variable and validate path

#2 Post by penpen » 06 Sep 2013 16:44

This may help you:

Code: Select all

setlocal enabledelayedExpansion
if not exist "!%~1!" (
   rem Environment variable links to invalid path:
   echo # PATH-ERROR #
   set %1 & pause
   endlocal
   exit 1
)
endlocal

That may help you too, if you don't like delayed expansion:

Code: Select all

((call dir "%%%~1%%" /A:D) 2>nul ) >nul
if errorlevel 1 (
   rem Environment variable links to invalid path:
   echo # PATH-ERROR #
   set %1 & pause
   exit 1
)


penpen

zickedi
Posts: 2
Joined: 06 Sep 2013 15:12

Re: Set environment variable and validate path

#3 Post by zickedi » 06 Sep 2013 17:33

Thanks, first version is just right and works. :D

Post Reply