windows - 使用 powershell 添加/删除主机文件条目会损坏文件

标签 windows powershell hosts

我正在尝试使用 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/

相关文章:

php - 在 7.0 ubuntu 16.04 旁边安装 php 5.6 后,本地虚拟主机停止工作

python - 在 Windows 10 上从 Python 获取准确的文件创建日期

python - Windows 上的 PySide2

windows - 从卷影副本备份

c# - 在 C# 中调用 PowerShell 脚本非常耗时

django - gunicorn、django 和 nginx 的静态文件

c++ - AdjustTokenPrivileges 错误 6 - 句柄无效

powershell - Get-ChildItem,通配符和过滤

node.js - 如何等待 powershell 命令在 node-powershell 中运行后再继续?

windows - 通过主机文件阻止网站不起作用?