为什么此脚本无法替换主机文件? [英] Why is this script failing to replace the hosts file?
问题描述
我们要更改要添加到站点的移动PC的主机文件.但是,客户端不太熟悉计算机,这就是为什么我想创建一个批处理文件来为它们进行更新的原因.
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.
由于要处理win 10和7,我们发现有时我们不能直接更新主机文件而不先复制它,然后覆盖原始文件. 因此,我认为可行的过程就是这样.
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.
- 带有原件复制日期的原件副本.
- 将主机复制到桌面.
- 更新桌面上的主机文件.
- 覆盖原始主机文件.
- 成功或失败的消息.
您可以看到该程序看起来并不那么困难,但是由于特权错误,我遇到了一个错误. 因此,由于客户的知识不足,我想尝试通过批处理文件来提升它.
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 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.
推荐答案
在使用提升的特权时,您似乎无法复制到%userprofile%\desktop
!
It seems that you cannot copy to %userprofile%\desktop
while using elevated privileges!
所以我只是将文件复制到drivers
文件夹,并且一切运行正常.
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
这篇关于为什么此脚本无法替换主机文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!