PowerShell - 使用 Get-Content 逐行粘贴内容而不是全部粘贴在一个文本中

PowerShell - 使用 Get-Content 逐行粘贴内容而不是全部粘贴在一个文本中

所以……我不是 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 ☺"

所以我的 hosts 文件最终如下所示:

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

提前致歉。评论和字符串都是我的母语,不是英语

答案1

主机写在一行上,因为您的代码没有循环遍历它们。我已将其添加foreach($line in $Hostname)到代码中。循环允许逐行将主机添加到文件中。

param([string]$DesiredIP = "127.0.0.1"
    ,$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 

foreach($line in $Hostname) {
Write-Host "Adding $desiredIP for $line in the hosts file" -ForegroundColor Gray

$escapedHostname = [Regex]::Escape($line)
$patternToMatch = If ($CheckHostnameOnly) { ".*\s+$escapedHostname.*" } Else { ".*$DesiredIP\s+$escapedHostname.*" }
If (($hostsFile) -match $patternToMatch)  {
    Write-Host $desiredIP.PadRight(20," ") "$line - not adding; is already in the hosts directory" -ForegroundColor DarkYellow
} else {
    Write-Host $desiredIP.PadRight(20," ") "$line - adding to the hosts file..." -ForegroundColor Yellow
    Add-Content -Encoding UTF8  $hostsFilePath ("$DesiredIP".PadRight(20, " ") + "$line")
}

}
    Write-Host " Done!"


Read-Host -Prompt "All Done! Press ENTER to close the window ☺"

笔记:我必须将输出翻译成英文才能理解发生了什么,并将它们保留在上面的代码中。您需要将它们改回您的语言。

相关内容