Valentina DG
Valentina DG

Reputation: 108

Batch script access denied even with admin privileges

I have a batch script in Windows7 to update the hosts file that fails. I am logged as a user with administrative rights.

Even if I run the script with the "Run as administrator" option I get Access denied. 0 files copied when executing this part of the script:

for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "IPv4"') do set ip=%%b
set ip=%ip:~1%

REM create changing part of hosts file...   
if exist %temp%\temp.txt del %temp%\temp.txt
echo %ip% myproxy >> %temp%\temp.txt  

REM check this...
set hostpath=C:\WINDOWS\system32\drivers\etc

REM add static part of hosts file
type "%hostpath%\hosts-static" >> %temp%\temp.txt

REM replace hosts file
copy /y %temp%\temp.txt "%hostpath%\hosts"

ipconfig /flushdns
netsh interface IP delete arpcache
pause

I also tried to create a shortcut and set the "Advanced -> Run as Administrator" option but no luck.

If I open a cmd shell as Administrator and then run the script from there everything works fine, but no way of running it directly double-clicking on the file (or its link). Any idea?


EDIT:

and it is also failing. From the same shortcut (without arguments) I can open a window where I can execute the batch correctly. I really cannot see why.

Upvotes: 6

Views: 26887

Answers (2)

Jake
Jake

Reputation: 21

Obviously a late response, but just solved this issue with a very straightforward solution so I thought I'd share:

Using ICACLS you can modify access control lists (ACLs) to bypass access denied errors. Run the following command:

ICACLS C:\path\to\batch\file\directory\* /C

the parameter /C tells the batch file to bypass access denied errors. Cheers.

Upvotes: 1

rojo
rojo

Reputation: 24466

Try attrib -r -s -h -a "%hostpath%\hosts" before your copy command. If any file is attributed +r, +s, or +h, you'll get "Access is denied" if you try to overwrite it using copy.

Upvotes: 0

Related Questions