Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Batch file 如何使用批处理文件向windows主机添加新行_Batch File_Append_Add_Hosts File - Fatal编程技术网

Batch file 如何使用批处理文件向windows主机添加新行

Batch file 如何使用批处理文件向windows主机添加新行,batch-file,append,add,hosts-file,Batch File,Append,Add,Hosts File,我知道这已经讨论过了,但我没有找到我需要的。 我需要在hosts窗口文件的末尾添加新行,但是, 首先,我需要检查这些行是否已经存在,然后添加它们 我试过这个: set "list=examp.com=examp2.com=examp3.com" SET NEWLINE=^0.0.0.0 for %%a in (%list%) do ( FINDSTR /I %%a %WINDIR%\system32\drivers\etc\hosts) IF %ERRORLEVEL% NEQ 0

我知道这已经讨论过了,但我没有找到我需要的。 我需要在hosts窗口文件的末尾添加新行,但是, 首先,我需要检查这些行是否已经存在,然后添加它们

我试过这个:

set "list=examp.com=examp2.com=examp3.com"
SET NEWLINE=^0.0.0.0
for %%a in (%list%) do  (
   FINDSTR /I %%a %WINDIR%\system32\drivers\etc\hosts)
   IF %ERRORLEVEL% NEQ 0 (ECHO %NEWLINE% %%a>>%WINDIR%\System32\drivers\etc\hosts)
   pause
但主机中的结果只有一行,如下所示:

0.0.0.0 %a
我还想知道是否有可能改变这一点:

set "list=examp.com=examp2.com=examp3.com"

另一个代码将从txt文件中获取变量。

您的代码并不像Mofi建议的那么糟糕。虽然使用等号作为
for
循环的分隔符是很少见的,但它仍然是合法的语法。我看到的最大的两个问题是,在
findstr
语句的末尾关闭
for
循环;并且,假设您解决了这个问题,
%ERRORLEVEL%
将需要延迟其扩展。或者您可以使用
if
语句的
if errorlevel
语法(有关详细信息,请参阅cmd控制台中的
help if
)。或者更好,使用条件执行

下面是一个使用条件执行的示例。本例还打开了一次附加的HOSTS文件,而不是每次循环迭代一次——这是一种微妙的效率改进,没错,但在使用循环编写文件时值得练习。由于主机默认设置了防止写入的属性,因此我存储并删除了主机文件的只读/system/hidden/etc.属性,将更改附加到文件中,然后将属性恢复到以前的状态

@echo off&setlocal
设置“hosts=%WINDIR%\system32\drivers\etc\hosts”
设置“list=examp.com=examp2.com=exam3.com”
设置“换行符=0.0.0.0”
对于/f“delims=“%%I in('attrib”%hosts%%'),请设置“raw=%%~I”
延迟扩展
对于(0,1,18)中的/L%%I,如果不是“!raw:~%I,1!”==”设置“attrs=!attrs!+!raw:~%I,1!”
endlocal&设置“attrs=%attrs%”
attrib-h-s-r-o-i-x-p-u“%hosts%”
>>%hosts%(
对于(%list%)中的%%a,请执行以下操作(
>NUL 2>NUL find/I“%%a”“%hosts%”| | echo(%NEWLINE%%%a
)
)
属性%attrs%%hosts%

有没有办法检查我们要添加的行是否已经存在?