Take the 2-minute tour ×

I want to check on whether the last character(s) of an environment variable are \ or .exe. How can I do this in Windows XP SP3?

share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

To use substrings:

set _parm1=foo.exe
if [%_parm1:~-1%]==[\] echo ends with \
if /i [%_parm1:~-4%]==[.exe] echo ends with .exe

You replace the number before the % sign to alter how many characters it checks at the end of the string.

share|improve this answer
+1 for remembering the substring syntax. –  grawity Mar 21 '11 at 16:44
It pays to read the help on all the cmd commands, especially set and for. They were improved tremendously in XP. While the syntax isn't easy to remember or easy to maintain when someone else created it, it will help you accomplish things when you are forced to do it with a batch file. It works on every windows system since XP, so it is something good to know. –  bruceatk Aug 31 '11 at 14:50
add comment

Don't do it, for your own sanity. Switch to PowerShell, Perl, Python, C#... even VBScript is acceptable.

:: call the subroutine defined below...
call :check "%somevariable%"
:: and check its exit code
if %ERRORLEVEL% equ 0 (
    echo Yes
) else (
    echo No

goto :eof

    if "%~nxi"=="" exit /b 0
    :: do a case-insensitive check because Windows would accept ".EXE"
    :: and ".Exe", so we should too.
    if /i "%~xi"==".exe" exit /b 0
    exit /b 1

For comparison, equivalent Python code:

if somevar.endswith("\\") or somevar.lower().endswith(".exe"):
share|improve this answer
add comment

Are you trying to do this programatically or just once?

If you want to see an environment variable once, typing echo %variablename% will work.

If you're trying to do it programatically, you'll probably need to use VBScript or soemthing similar to do the required string manipulation. There should be an example in the MS Script Repository that can get you started, depending on exactly what you're looking to do with the variable once you isolate it.

share|improve this answer
add comment

Your Answer


