我需要一个批处理文件来在Windows中添加记录到hosts文件,但是我不仅仅需要追加写入文件,因为我想检查这个记录是否已存在。这可能吗?
我需要一个批处理文件来在Windows中添加记录到hosts文件,但是我不仅仅需要追加写入文件,因为我想检查这个记录是否已存在。这可能吗?
type "%SystemRoot%\system32\drivers\etc\hosts" | find "my_record" ||echo my_record>>"%SystemRoot%\system32\drivers\etc\hosts"
尝试这个。您需要管理员权限才能在hosts文件中添加内容。
FINDSTR
版本。 - npocmakaecho\>>"%SystemRoot%\system32\drivers\etc\hosts&&echo my_record>>"%SystemRoot%\system32\drivers\etc\hosts""
。请注意Foxidrive提到的内容,并使用整个命令来查找记录。 - npocmakaATTRIB
或CACLS
吗? - npocmaka这有点棘手。
首先,我建议您放弃使用批处理文件来完成此操作。
仅凭批处理文件本身无法做任何类似的事情,除非与外部工具一起使用。
虽然这是可能的,但除非您知道需要安装哪些命令行工具以及如何搭配使用,否则您将不断进行尝试。
如果您确实想要这样做,那么我建议您查看sourceforge上的GnuWin32项目,他们已将所有标准unix命令行工具移植到windows系统中,其中包括sed、grep、awk等工具,非常适合您所需的操作。
然而,我强烈建议您考虑使用Powershell,或者如果您有.NET经验,则可以使用C#编写命令行工具。
我暂时想不出powershell的例子,但您可以使用C#编写如下代码:
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
static void Main()
{
const string filename = "path\to\your\hosts\file";
List<string> lines = new List<string>();
using (StreamReader reader = new StreamReader(filename))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
}
string newLineToAdd = "127.0.0.1 somedomain.com"
bool found = false;
foreach(string line in lines)
{
if(line.Equals(newLineToAdd))
{
found = true;
}
}
if(!found)
{
lines.Add(newLineToAdd);
}
using (StreamWriter writer = new StreamWriter(filename))
{
foreach(string line in lines())
{
writer.WriteLine(line);
}
}
}
}
基于npocmaka的代码的建议:
for /f "tokens=1*" %%i in ("%my_record%") do type "%SystemRoot%\system32\drivers\etc\hosts" | find "%%i" | find "%%j" >nul||echo %my_record%>>"%SystemRoot%\system32\drivers\etc\hosts"
这并没有解决虚假IP匹配的问题。