Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if command is internal in CMD

I have a command's name and I need to check if this command is internal. How can I do it in a batch script?

like image 998
michaeluskov Avatar asked Dec 21 '22 14:12

michaeluskov


1 Answers

So after a lot of tweaking, and thanks to the help of @Andriy M, it finally works.

@ECHO off

CALL :isInternalCommand dir dirInternal
ECHO is dir internal: %dirInternal%

CALL :isInternalCommand find findInternal
ECHO is find internal: %findInternal%

exit /b 0

:isInternalCommand
SETLOCAL

MKDIR %TEMP%\EMPTY_DIR_FOR_TEST > NUL 2>& 1
CD /D %TEMP%\EMPTY_DIR_FOR_TEST
SET PATH=
%~1 /? > NUL 2>&1
IF ERRORLEVEL 9009 (ENDLOCAL
SET "%~2=no"
) ELSE (ENDLOCAL
SET "%~2=yes"
)

GOTO :EOF

OLD SOLUTION

You can use where. If it fails, the command is probably internal. If it succeeds, you get the executable path that proves it's not internal.

C:\Users\user>where path
INFO: Could not find files for the given pattern(s).

C:\Users\user>where find
C:\Windows\System32\find.exe

EDIT: As the comments suggest, this might not be the best solution if you're looking for portability and not just research. So here's another possible solution.

Set %PATH% to nothing so HELP can't find anything and then run HELP on the command you're trying to check.

C:\Users\user>set PATH=

C:\Users\user>path
PATH=(null)

C:\Users\user>%WINDIR%\System32\help del
Deletes one or more files.

DEL [/P] [/F] [/S] [/Q] [/A[[:]attributes]] names
[...]

C:\Users\user>%WINDIR%\System32\help find
'find' is not recognized as an internal or external command,
operable program or batch file.

This might still fail if the command doesn't have help.

EDIT 2: Never mind, this won't work either. Both cases return %ERRORLEVEL%=1.

like image 94
kichik Avatar answered Jan 02 '23 03:01

kichik