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
Ok, so how about...
> 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.
I've read something about internal commands not setting ERRORLEVEL, but copy
obviously seems to do so in the last case.
You can write
copy %0 foo
to copy the batch file itself.This will always exist.
Remember to delete the file afterwards, and to make sure that you aren't overwriting an existing file by that name.
There ought to be a better way to do this, but I don't know of any.
EDIT: Better yet, try
mkdir foo
.In case the batch file is running off a network (or if it's very large), this may be faster.
i found that executing
copy
within the batch file echoed an error to STDERR, but left%ERRORLEVEL%
untouched (still 0). so the workaround was to combine the command with a conditional execution ofset
.this is tested on XP and 7 and seems to work reliably.
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.
In CMD type
CACLS /?
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.EDIT: You can use directory name as well.
So to do a check, you would:
An extension to Mechaflash's answer, and solves the problem of overwriting the file by generating a unique filename for the "testing" file.
(
%~1
is the input directory)EDIT: If you want a more safe option