我正在尝试使用Powershell在Windows主机文件中添加或删除特定条目,但是当我这样做时,它会工作一段时间,然后过一会儿再次进行编辑(我猜是在Windows读取时) ,并且它已损坏(显示汉字)。
我尝试使用我发现的here代码的一部分。 它可以让我正确地编辑文件,并且输入有效,直到损坏为止。
我这样做是为了添加条目:
If ((Get-Content "$($env:windir)\system32\Drivers\etc\hosts" ) -notcontains "111.111.111.111 example.com")
{ac -Encoding UTF8 "$($env:windir)\system32\Drivers\etc\hosts" "111.111.111.111 example.com" }
Here是文件损坏后的样子:
感谢您的帮助。
已解决:
删除-Encoding UTF8
答案 0 :(得分:2)
因为在主机文件的注释中指出,“ IP地址和主机名应至少用一个空格分隔。”,试图找到一个只有一个空格的字符串中间的字符可能返回false。
我认为最好使用Regex,因为它允许匹配多个空格字符以将IP与主机名分开。
但是,这确实需要在条目的两个部分都使用[Regex]::Escape()
,因为它们包含正则表达式特殊字符(点)。
类似这样的东西:
$hostsFile = "$($env:windir)\system32\Drivers\etc\hosts"
$hostsEntry = '111.111.111.111 example.com'
# split the entry into separate variables
$ipAddress, $hostName = $hostsEntry -split '\s+',2
# prepare the regex
$re = '(?m)^{0}[ ]+{1}' -f [Regex]::Escape($ipAddress), [Regex]::Escape($hostName)
If ((Get-Content $hostsFile -Raw) -notmatch $re) {
Add-Content -Path $hostsFile -Value $hostsEntry
}