简体   繁体   English

如何在批处理文件中的变量中获取文件的位置?

[英]How to get the location of a file in a variable in a batch file?

Windows Command prompt Query: I have a root directory "A". Windows命令提示符查询:我有一个根目录“A”。 There are several other sub-directories inside "A". “A”中有几个其他子目录。 Now somewhere inside these directories there is a file called "setup.exe". 现在这些目录中的某个地方有一个名为“setup.exe”的文件。 Now I want the complete path from A till the file. 现在我想要从A到文件的完整路径。 I will need this path later in my batch file. 稍后我将在批处理文件中使用此路径。 So I want it to be stored in some variable. 所以我希望它存储在一些变量中。 I have found ways to get the path but not able to store it to some variable. 我找到了获取路径但无法将其存储到某个变量的方法。

Kindly help. 请帮助。

Try this,it may help you. 试试这个,它可能对你有帮助。

for /r "C:\directory path" %%a in (*) do if "%%~nxa"=="setup.exe" set variable_to_store_path=%%~dpnxa
if defined variable_to_store_path (
echo %variable_to_store_path%
) else (
echo File not found
)

Let command DIR find setup.exe in directory tree and use command FOR to process the output of DIR to assign the found setup.exe with full path to an environment variable. 让命令DIR在目录树中找到setup.exe并使用命令FOR处理DIR的输出,以便为找到的setup.exe分配环境变量的完整路径。

@echo off
set "SetupFile="
for /F "delims=" %%# in ('dir C:\a\setup.exe /A-D /B /S 2^>nul') do set "SetupFile=%%#"
if "%SetupFile%" == "" (
    echo Could not find setup.exe.
) else (
    echo Found %SetupFile%
)

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully. 要了解使用的命令及其工作方式,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • echo /?
  • dir /?
  • for /?
  • if /?
  • set /?

See also Using command redirection operators to understand suppressing the error message of command DIR output to STDOUT on not finding any setup.exe by redirecting the error message to device NUL with 2>nul with escaping redirection operator > with ^ to be applied on execution of command DIR instead of producing a syntax error because a redirection specified within set / command / file specification of command FOR is not possible. 另请参阅使用命令重定向操作符来了解抑制命令DIR输出的错误消息到STDOUT上没有发现任何setup.exe通过与重定向错误消息到设备NUL 2>nul与逸出重定向操作符>^上的执行来施加命令DIR而不是产生语法错误,因为在命令FOR的 set / command / file规范中指定的重定向是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM