如何在批处理脚本中检查文件/目录是否可写
在 bash 中,我会使用
[ -w ... ]
Windows 批处理文件的等效项是什么?
In bash, I would use
[ -w ... ]
What's the equivalent for Windows batch files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
据我所知,您可以查明该文件是否 存在与否,但除了尝试在其上写入之外,无法知道它是否可写。这不仅仅是没有 R 标志的问题;还涉及网络和 NTFS 权限(可能还涉及组策略)。
如果您可以重写代码,则可以通过 错误级别。
As far as I know, you can find out whether the file exists or not, but there's no way to know if it's writeable, apart from trying to write on it. It's not only a matter of not having the R flag; network and NTFS permissions are involved as well (and probably group policies too).
If you can rewrite your code, you can capture the return code of the write operation trough the errorlevel.
抱歉各位在这里插嘴。
这可能不是 100% 您正在寻找的内容,但我已将其与 Apache Tomcat 的正在使用的日志文件一起使用,并且它工作得绝对完美。
感谢@dbenham 提供的出色代码! https://stackoverflow.com/a/10520609/175063
Sorry folks for chiming in here..
This may not be 100% what you are looking for, but I have used this with in-use log files for Apache Tomcat and it works absolutely perfectly.
Thanks to @dbenham for his awesome code! https://stackoverflow.com/a/10520609/175063
这是旧的,但我没有在这里找到它:
lock.bat
test.bat
move
不会更改文件创建/更改/访问次数。https://www.dostips.com/forum/viewtopic.php?t= 5542
要检查目录的访问权限,您可以使用
rename
命令以相同的方式进行操作:要测试它,只需添加
path\
-拒绝
。所有人
的所有This is old but I didn't found it here:
lock.bat
test.bat
The
move
does not change a file create/change/access times.https://www.dostips.com/forum/viewtopic.php?t=5542
To check the access rights to a directory you can go the same way with the
rename
command:To test it just add for
path\
-deny all
forEveryone
.这样做
你可以使用 vbscript save as check.vbs 并在命令行上
you can do it like this using vbscript
save as check.vbs and on command line
我发现的最可靠的方法是将 NUL 复制到目标目录中的文件中。
如果该目录不存在或者当前用户不可写入该目录,则将以 1 退出。
我使用 /B 因为 NUL 是二进制文件,而 /Y 则覆盖现有文件。
The most reliable method I have found is to copy NUL to a file in the target directory.
This will exit with 1 if the directory does not exist or if the directory is not writable by the current user.
I use /B as NUL is binary and /Y to overwrite the existing file.
输出 -r--r--r-- 表示不可写文件
输出 -rw-r--r-- 对于可写文件,
您可以存储该值并检查第三个字符是否为“w”(表示可写)或“-”(表示不可写)。
在条件语句中使用诸如
%myVar:~2,1%
之类的语法。不确定这对操作系统有何影响。
outputs -r--r--r-- for a not writable file
outputs -rw-r--r-- for a writable file
you could store the value and check if the 3rd character is "w" for writable or "-" for not writable.
using some syntax like
%myVar:~2,1%
in a conditional statement.not sure how OS dependent this would be.