'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:

  • added the whole script.

  • I tried creating a shortcut for the following command to execute as Administrator

    C:\Windows\System32\cmd.exe /c script.bat

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.



Solution 1:[1]

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.

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rojo
Solution 2 Cristian Ciupitu