Page 1 of 1

Read the directory of a bat file when you run it as admin

Posted: 07 Sep 2014 04:53
by autonicknan
Hello,

I am trying to create a new file and save some info in it like below:

.
.
.
if exist %user% (
echo The username you provided already exists!!
pause >nul
goto create
)else (
md "C:\Users\nikos\Desktop\Batch_Programming\Database\%user%"
cd "C:\Users\nikos\Desktop\Batch_Programming\Database\%user%"
)

echo set user=%user% >> %user%.sav
echo set pass=%pass% >> %user%.sav

echo Your account was succesfully created!
pause >nul


Unfortunately this fails with Access Denied.
Any idea why this happens?

If I run the bat file as administrator it works but the problem I face is that the directory the work is done is C:\Windows\System32.
I easily overcame this with cd command at the begin of the script, but I wonder whether there is any way to read the directory of a the batch file?

Thanks
Nikos

Re: Read the directory of a bat file when you run it as admi

Posted: 07 Sep 2014 04:59
by foxidrive
These changes should help. Note that the when eching %user% and %pass% that it can contain an & and possibly other poison characters and fail.


cd /d "%~dp0"

if exist "%user%.sav" (
echo The username you provided already exists!!
pause >nul
goto create
)spaceelse (
md "%userprofile%\Desktop\Batch_Programming\Database\%user%" 2>nul
cd /d "%userprofile%\Desktop\Batch_Programming\Database\%user%"
)

">> %user%.sav" echo set user=%user%
">> %user%.sav" echo set user=%pass%

echo Your account was succesfully created!
pause >nul