为什么程序从批处理文件运行时不工作,但点击运行时却正常
Why a program doesn't work when run from a batch file, but works when clicked

原始链接: https://devblogs.microsoft.com/oldnewthing/20261026-00/?p=112797/

Explorer 会把启动程序的当前目录设置为包含被双击文件的文件夹,帮助程序找到相关的辅助文件。通过完整路径运行程序的批处理文件可能留下错误的当前目录,导致这些文件被遗漏。客户确认这就是问题所在,并使用 pushd/popd 修复了它。一个可能的替代原因是 App Paths 条目向 PATH 添加了目录。

Hacker News 最新 | 过往 | 评论 | 提问 | 展示 | 工作 | 提交 登录 为什么程序从批处理文件运行时不起作用,但点击时却可以 (devblogs.microsoft.com/oldnewthing) 25 分 由 ibobev 2小时前 | 隐藏 | 过往 | 收藏 | 讨论 帮助 考虑申请 YC 2027 冬季批次!申请开放至 11 月 2 日。 指南 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文

A customer asked for help writing a batch file to launch a program. For some reason, the program displayed an error message when the batch file ran it, whereas it worked fine when they double-clicked the program from Explorer.

I immediately suspected that they were not setting the current directory.

Some time ago, I noted that when you double-click a file in Explorer, Explorer sets the current directory of the program to the directory containing the thing that you double-clicked. This is done to accomodate programs that look for ancillary files in the current directory. The example I had was a hypothetical LitWare Writer program that, when given an ABC.LIT file, looks for related files like ABC.LTC (the table of contents) and ABC.LDC (the custom dictionary) in the current directory.

This also happens if you double-click the .exe file: The current directory is set to the directory that contains the executable.

My guess is that the customer’s program looks for ancillary files relative to its current directory, but the batch file ran the program by its full path without changing the current directory to match the program’s path.

The customer confirmed that explicitly changing the directory fixed the program. (More specifically, they used pushd to change the directory and then popd to restore the original directory.)

Bonus chatter: It didn’t come to it, but my second idea would have been to check whether the program had set a custom entry under App Paths to ask for additional directories to be added to the PATH environment variable when the program is run.

联系我们 contact @ memedata.com