所以.. 我不是 PowerShell 脚本方面的专家.. 我得到了这个脚本,我正在尝试将网站列表添加到 hosts 文件中以进行阻止。我似乎无法弄清楚如何让它逐行添加每个域,而不是一行中的所有内容。
我想知道是否有人可以帮助我或指出我正确的方向。
这是我的代码:
param([string]$DesiredIP = "127.0.0.1"
,[string]$Hostname = @(Get-Content ".\src\hosts")
,[bool]$CheckHostnameOnly = $false)
#Bætir við færslu í HOSTS skránna.
#Krefst -RunAsAdministrator
$hostsFilePath = "$($Env:WinDir)\system32\Drivers\etc\hosts"
$hostsFile = Get-Content $hostsFilePath
Write-Host "Verið að bæta við $desiredIP fyrir $Hostname í hosts skránna" -ForegroundColor Gray
$escapedHostname = [Regex]::Escape($Hostname)
$patternToMatch = If ($CheckHostnameOnly) { ".*\s+$escapedHostname.*" } Else { ".*$DesiredIP\s+$escapedHostname.*" }
If (($hostsFile) -match $patternToMatch) {
Write-Host $desiredIP.PadRight(20," ") "$Hostname - not adding; er nú þegar í hosts skránni" -ForegroundColor DarkYellow
}
Else {
Write-Host $desiredIP.PadRight(20," ") "$Hostname - að bæta við í hosts skránna... " -ForegroundColor Yellow
Add-Content -Encoding UTF8 $hostsFilePath ("$DesiredIP".PadRight(20, " ") + "$Hostname")
Write-Host " Búið!"
}
Read-Host -Prompt "Allt Klárt! Ýttu á ENTER til að loka glugganum ☺"
所以我的主机文件最终如下:
127.0.0.1 website.com test.com google.com pirates.net loremipsum.org filler.co.uk en.kremlin.ru test.com testing.com
我从中获取列表的 .\src\hosts 文件如下所示:
website.com
test.com
google.com
pirates.net
loremipsum.org
filler.co.uk
en.kremlin.ru
test.com
testing.com
提前道歉。评论和字符串是我的母语,不是英语
主机写在一行上,因为您的代码没有循环通过它们。我已添加
foreach($line in $Hostname)
到代码中。该循环允许将主机逐行添加到文件中。注意:我必须用英语翻译输出以了解发生了什么并将它们保存在我上面的代码中。您需要将它们改回您的语言。