问题
We want to make a change to hosts file of our mobile PC we are adding to our sites. However the client isn't so well versed with computers, that's why I wanted to create a batch file to do the update for them.
The idea is to -Make a copy of the original with the date it was copied. -Update the hosts file.
Due to dealing with win 10 and 7 we found out sometimes we cant straight update the hosts file without copying it first and then override the original. Therefore the procedure I thought would work is this.
- Copy of the original with the date it was copied.
- Copy the hosts to desktop.
- Update the hosts file on desktop.
- override the original hosts file.
- message if success or failed.
You can see the program doesn't look so difficult, but I encountered an error due to privileges error. So due to our clients having not enough knowledge, I wanted to try and elevate it though my batch file.
I'v tied searching here and found a post "How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?". But unfortunately my VBS and batch knowledge isn't that high and I hoped someone might help me decipher it.
The code I'v created:
::the copy to desktop command xcopy /s C:\Windows\System32\drivers\etc\hosts %userprofile%\desktop
::the update of hosts file
echo www.qpv-view.info xxx.xxx.xxx.xxx >hosts
::the date for the copied hosts file
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2% set stamp=Oldhosts_%YYYY%%MM%%DD%
copy /y C:\Windows\System32\drivers\etc\hosts C:\Windows\System32\drivers\etc\%stamp%
::The override of the updated file
move /s/Y %userprofile%\desktop\hosts C:\Windows\System32\drivers\etc
end
When I launch, the copy works fine. However the update part requires elevated privileges. However if I start the script with elevated privileges the copy doesn't occur.
回答1:
Because stamp
is not defined, this line will copy the hosts file over itself:
copy /y C:\Windows\System32\drivers\etc\hosts C:\Windows\System32\drivers\etc\%stamp%
Because it is equivalent to:
copy /y C:\Windows\System32\drivers\etc\hosts C:\Windows\System32\drivers\etc\
回答2:
It seems that you cannot copy to %userprofile%\desktop
while using elevated privileges!
So I just copied the file to drivers
folder and all ran fine.
@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set stamp=Oldhosts_%YYYY%%MM%%DD%
copy /y C:\Windows\System32\drivers\etc\hosts C:\Windows\System32\drivers\etc\%stamp%
copy /y C:\Windows\System32\drivers\etc\hosts C:\Windows\System32\drivers
echo www.qpv-view.info 172.16.10.60 >C:\Windows\System32\drivers\hosts
move /y C:\Windows\System32\drivers\hosts C:\Windows\System32\drivers\etc
pause
来源:https://stackoverflow.com/questions/60198999/why-is-this-script-failing-to-replace-the-hosts-file