检查目录是否在BAT脚本中可写的最佳方法? [英] Best way to check if directory is writable in BAT script?
问题描述
如何检查执行用户是否可以从批处理脚本中写入目录?
How can I check whether a directory is writable by the executing user from a batch script?
这是我到目前为止尝试过的:
Here's what I've tried so far:
> cd "%PROGRAMFILES%"
> echo. > foo
Access is denied.
> echo %ERRORLEVEL%
0
好吧,那...
> copy NUL > foo
Access is denied.
> echo %ERRORLEVEL%
0
不是吗?那怎么...
Not that either? Then what about...
> copy foo bar
Access is denied.
0 file(s) copied.
> echo %ERRORLEVEL%
1
这有效,但是如果文件不存在,则会中断.
This works, but it breaks if the file doesn't exist.
我已经读过一些关于内部命令的信息,但没有设置ERRORLEVEL,但是copy
显然在最后一种情况下是这样做的.
I've read something about internal commands not setting ERRORLEVEL, but copy
obviously seems to do so in the last case.
推荐答案
一定要针对它运行命令,以查找是否被拒绝是执行此操作的简便方法.您还可以使用CACLS来查找权限到底是什么还是没有权限.这是一个示例.
Definitely running a command against it to find if its denied is the easy way to do it. You can also use CACLS to find exactly what the permissions are or aren't. Here's a sample.
在CMD中,键入CACLS /?
CACLS "filename"
将为您提供文件当前允许的权限.
R =读,W =写,C =更改(与写相同?),F =完全访问.
CACLS "filename"
will give you what the current permissions is allowed on the file.
R = Read, W = Write, C = Change (same as write?), F = Full access.
您也可以使用目录名称.
You can use directory name as well.
要进行检查,您将:
FOR /F "USEBACKQ tokens=2 delims=:" %%F IN (`CACLS "filename" ^| FIND "%username%"`) DO (
IF "%%F"=="W" (SET value=true && GOTO:NEXT)
IF "%%F"=="F" (SET value=true && GOTO:NEXT)
IF "%%F"=="C" (SET value=true && GOTO:NEXT)
SET value=false
)
ECHO This user does not have permissions to write to file.
GOTO:EOF
:NEXT
ECHO This user is able to write to file.
这篇关于检查目录是否在BAT脚本中可写的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!