我正在尝试使用 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文件损坏后的样子:
感谢您的帮助。
已解决:
删除 -编码 UTF8
最佳答案
因为正如hosts文件的注释中所说,“IP地址和主机名应该至少用一个空格分隔。”,试图找到一个恰好有一个空格的字符串之间的字符可能返回 false。
我认为最好使用正则表达式,因为它允许匹配多个空格字符以将 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
}
关于windows - 使用 powershell 添加/删除主机文件条目会损坏文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56724808/