检测文件是否在批处理文件打开 [英] Detecting if a file is open in a batch file

查看:283
本文介绍了检测文件是否在批处理文件打开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有用于执行长构建一个批处理文件,并在最后它创建了一个EXE。如果我忘记关闭应用程序下来之前,我开始构建,链接阶段失败时,它无法重新创建EXE。

Say I have a batch file for carrying out a long build and at the end it creates an EXE. If I forget to close the app down before I start the build, the link phase fails when it can't re-create the EXE.

我要检查,如果EXE的营业时间的启动的构建中。我试图重命名的EXE文件本身,但尽管这给出了一个拒绝访问错误rename命令(即一个内部命令),不设置%ERRORLEVEL%。

I want to check if the EXE is open at the start of the build. I tried renaming the EXE file to itself but although this gives an access denied error the rename command (being an internal command) doesn't set %ErrorLevel%.

什么检查,设置一个打开的文件的非破坏性的方法%ERRORLEVEL%至非零值α

What's a non-destructive way of checking for an open file that sets %ErrorLevel% to a non-zero value?

推荐答案

重命名方法对我来说没有工作(在Windows XP SP3测试)。我开始一个任意应用程序,并试图将其重命名为自身。没有错误,没有影响任何责任。

The rename method didn't work for me (tested on Windows XP SP3). I started an arbitrary application and tried to rename it to itself. There was no error, no effect whatsoever.

不过,这种方法没有工作:

However, this method did work:

COPY /B app.exe+NUL app.exe

在该应用程序正在运行,这个命令我产生一个错误信息。而当应用程序是不接合的,不仅是这个命令preserved文件的内容,但它也离开了修改时间不变。

When the application was running, this command produced me an error message. And when the application was unengaged, not only this command preserved the contents of file, but it also left the modification timestamp unchanged.

如果我是你,所以,我可能会以这种方式使用此命令(在批处理脚本的开始,像你说的):

If I were you, therefore, I would probably use this command (at the beginning of the batch script, like you said) in this way:

COPY /B app.exe+NUL app.exe >NUL || (GOTO :EOF)

|| 使用者将控制权。如果previous命令失败旁边的命令/块(上调ERRORLEVEL值)。因此,上面的命令将终止脚本,如果COPY失败(这会如果文件被打开)。

The || operator passes the control to the command/block next to it if the previous command has failed (raised the errorlevel value). Therefore, the above command would terminate the script if COPY failed (which it would if the file was open).

该错误消息将是preserved(因为这样的消息通常被发送到所谓的标准错误设备,并没有与&GT丢弃; NUL 重定向,而其他非错误消息通常发送到标准输出,因此可以与pssed燮$ p $ > NUL ),并作为$ p的解释脚本$ pmature终止。但是,如果你想显示自己的消息,而不是,你可以尝试这样的事:

The error message would be preserved (because such messages are usually sent to the so called standard error device and are not discarded with the >NUL redirection, while other, non-error messages are typically sent to the standard output and so can be suppressed with >NUL) and serve as an explanation of the premature termination of the script. However, if you want to display your own message instead, you can try something like this:

COPY /B app.exe+NUL app.exe >NUL 2>NUL || (ECHO Target file inaccessible& GOTO :EOF)

> NUL 隐藏无论是发送到标准输出, 2 - ; NUL 做为同标准误差

While >NUL hides whatever is sent to the standard output, 2>NUL does the same for the standard error.

这篇关于检测文件是否在批处理文件打开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆