views:

156

answers:

2

I want to have my batch file to recognise the extension of the file the user types in in the following situation:

The user has to type in a folder OR a .zip/.rar file.

if its a folder, it should use GOTO :folder if its a .zip/.rar, it should use GOTO :ziprar

(if it is possible without 3rd party software, than dont going to say about it please)

+3  A: 

You can extract substrings from environment variables, which you can use to get the file extension:

set FILENAME=C:\mypath\myfile.rar
if "%FILENAME:~-4%"==".rar" (
  echo It is a RAR file!
) else (
  echo Not a RAR file
)
thanks, works like a charm
YourComputerHelpZ
+1  A: 

If the user can specify the path as a parameter to the batch file, that is the best option since "%~1" is less problematic than "%filename%" like I said in a comment to Helen's answer. It would look something like:

setlocal ENABLEEXTENSIONS
FOR %%A IN ("%~1") DO (
    IF /I "%%~xA"==".rar" goto ziprar
    IF /I "%%~xA"==".zip" goto ziprar
)
goto folder

If you can't use a parameter, the best I could come up with is:

setlocal ENABLEEXTENSIONS
REM set file="f~p 'o%OS%!OS!^o%%o.rar"
set /p file=Enter a folder path or a zip/rar file name: 
FOR /F "tokens=*" %%A IN ("%file%") DO (
    IF /I "%%~xA"==".rar" goto ziprar
    IF /I "%%~xA"==".zip" goto ziprar
)
goto folder

There is a possibility that there is a valid filename that causes syntax errors, but I did not find one during my limited testing.

You might also want to consider a basic folder check rather than checking file extensions:

IF EXIST "%~1\*" (goto folder) ELSE goto ziprar
Anders