I'm writing a batch file for Windows and use the command 7z
(7-Zip). I have put the location of it in the PATH. Is there a relatively easy way to check whether the command is available?
Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.
To open the BAT file in Notepad, right-click it and choose Show more options > Edit from the menu (or just Edit in some Windows versions). You might find it helpful to use more advanced text editors that support syntax highlighting when editing a BAT file.
Do not execute the command to check its availability (i.e., found in the PATH
environment variable). Use where
instead:
where 7z.exe >nul 2>nul
IF NOT ERRORLEVEL 0 (
@echo 7z.exe not found in path.
[do something about it]
)
The >nul
and 2>nul
prevent displaying the result of the where
command to the user. Executing the program directly has the following issues:
You can also define a routine, which can help users ensure their system meets the requirements:
rem Ensures that the system has a specific program installed on the PATH.
:check_requirement
set "MISSING_REQUIREMENT=true"
where %1 > NUL 2>&1 && set "MISSING_REQUIREMENT=false"
IF "%MISSING_REQUIREMENT%"=="true" (
echo Download and install %2 from %3
set "MISSING_REQUIREMENTS=true"
)
exit /b
Then use it such as:
set "MISSING_REQUIREMENTS=false"
CALL :check_requirement curl cURL https://curl.haxx.se/download.html
CALL :check_requirement svn SlikSVN https://sliksvn.com/download/
CALL :check_requirement jq-win64 jq https://stedolan.github.io/jq/download/
IF "%MISSING_REQUIREMENTS%"=="true" (
exit /b
)
PowerShell:
On PowerShell
, the Get-Command
cmdlet can be considered to be the equivalent of cmd's where.exe
.
Get-Command <cmd>
IF ($? -ne $true)
{
Write-Host "<cmd> not found in path"
# Do something about it
}
Yup:
@echo off
set found=
set program=7z.exe
for %%i in (%path%) do if exist %%i\%program% set found=%%i
echo "%found%"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With