【问题标题】:How to use Windows Command Line to search for file, then create text document with location?如何使用 Windows 命令行搜索文件,然后创建带有位置的文本文档?
【发布时间】:2012-06-15 21:17:59
【问题描述】:

我正在编写我的第一个批处理文件,由于我以前从未使用过 Windows 命令行,因此遇到了一些问题。

这是我的场景。我在几个图像上使用这个批处理文件来安装一些东西。我希望批处理文件检查安装程序应该位于的文件夹,如果不存在,我希望批处理文件在计算机中搜索安装程序。之后,我希望它运行上述安装程序。

这是我所拥有的:

ECHO.
ECHO Starting Foo installation

IF EXIST Install\Installer.cmd (CALL Install\Installer.cmd & GOTO NextPart) ELSE (GOTO SearchInstaller)

:SearchInstaller
SET the_path =
E: & CD\
DIR /S/B Installer.cmd > installer_location.txt
IF EXIST installer_location.txt (SET /P the_path =< installer_location.txt & GOTO FoundIt)
C: & CD\
DIR /S/B Installer.cmd > installer_location.txt
IF EXIST installer_location.txt (SET /P the_path =< installer_location.txt & GOTO FoundIt)
D: & CD\
DIR /S/B Installer.cmd > installer_location.txt
IF EXIST installer_location.txt (SET /P the_path =< installer_location.txt & GOTO FoundIt)
ECHO Installation file not found.

:FoundIt
ECHO Batch file found at%the_path%
CALL %the_path%
ECHO Finished installation & ECHO. 
GOTO NextPart

:NextPart
(more stuff)

我认为问题在于,一旦我使用 DIR 定位它,它就没有保存路径。我已经研究了好几天,我的谷歌搜索都充满了紫色链接。我发现的一切都表明我的语法是正确的,但我知道我做错了什么。

我已经尝试在多个位置放置ECHO Program execution reached this point.,所以我至少知道它会到达哪里。我看到的问题在于将文本文件的内容分配给the_path 的行以及我尝试ECHO 路径的行,所以我可以看到它有效。

【问题讨论】:

  • 我会说,只要您有任何重要的 if 或 ANY 循环停止使用批处理文件。我开始学习python就是为了这种事情。或者选择任何其他(非 powershell :-) 脚本(它可能与 msbuild 一起使用),你会更快乐,更有效率
  • 我很想(我喜欢 Python),但我暂时还是坚持使用批处理。
  • 我认为这不会在 C: 或 D: 驱动器上找到 cmd 文件,因为在找不到E: 驱动器上的文件。
  • !!这可能是个问题......我假设如果它没有找到文件,它就没有创建 .txt
  • 我可以——而不是检查文本是否已创建——而是检查文本文件的大小,并针对 0 进行测试吗?命令式说话能做到吗?

标签: windows file search command-line


【解决方案1】:

在您的SET /P 命令中,变量名和等号之间有一个空格。这完全符合您的要求,而不是您想要的:它设置了一个名称以空格结尾的变量。去掉多余的空格,我认为它会起作用。

补充:-

为了避免 Neil 指出的问题(很好!)试试这个:

DIR /S/B Installer.cmd > installer_location.txt
SET /P the_path=< installer_location.txt
if defined the_path goto :foundit

事实证明,如果未找到 installer.cmd,则 installer_location.txt 为空且未定义 the_path。如果您想格外小心,请尝试

if defined the_path if exist "%the_path%" goto :foundit

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 2020-10-31
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    相关资源
    最近更新 更多