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
##
Set environment variable and validate path
Moderator: DosItHelp
Re: Set environment variable and validate path
This may help you:
That may help you too, if you don't like delayed expansion:
penpen
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
Re: Set environment variable and validate path
Thanks, first version is just right and works. 
