Powershell 脚本用于清除 localhost 行后的文本并将静态主机名和当前 IP 地址添加到文件中

Powershell 脚本用于清除 localhost 行后的文本并将静态主机名和当前 IP 地址添加到文件中

需要清除 PowerShell 中 127.0.0.1 localhost 主机文件行之后的所有文本。最后一行是主机文件中此行之后的 localhost 条目,我想删除所有文本行,可以吗?以下是代码。

Set-ExecutionPolicy -ExecutionPolicy Unrestricted 

$ip = get-WmiObject Win32_NetworkAdapterConfiguration|Where {$_.Ipaddress.length -gt 1} 

$ip.ipaddress[0]
$hst = $env:COMPUTERNAME
$hostfile = Get-Content "$($env:windir)\system32\Drivers\etc\hosts"
if ($hostfile -notcontains "127.0.0.2 hostname1" -and 
    (-not($hostfile -like "$($ip.ipaddress[0]) $hst"))) {
    Add-Content -Encoding UTF8 "$($env:windir)\system32\Drivers\etc\hosts" "$($ip.ipaddress[0]) $hst" 
}

答案1

此脚本会删除之后的所有内容127.0.0.1 localhost并将其保存回文件。如果您的条件为真,则会在将文件写回磁盘之前注入新条目。

代码:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted 

$ipAdresses = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object {$_.IPAddress.length -gt 0} | Select-Object -Property 'IPAddress' -First 1

$ip = $ipAdresses.IPAddress[0]
$hst = $env:COMPUTERNAME
$hostFilePath = "$($env:windir)\system32\Drivers\etc\hosts"
$hostfile = Get-Content -Path $hostFilePath
$newHostFileEntry = "{0} {1}" -f $ip, $hst

# Delete all text after what is defined as $matchString
$lastIndexOfNewArray = 0
$matchString = '127.0.0.1\s+localhost'

for ($index = 0; $index -lt $hostfile.Count; $index++) {
    if ($hostfile[$index] -match $matchString) {
        $lastIndexOfNewArray = $index
        break
    }
}
$newHostFileContent = $Hostfile[0..$lastIndexOfNewArray]

# Adds entry for local IP address if conditions resolve to $true
if ($newHostFileContent -notcontains "127.0.0.2 hostname1" -and 
    (-not($newHostFileContent -like $newHostFileEntry))) {
        $newHostFileContent = New-Object System.Collections.ArrayList(,$newHostFileContent)
        $newHostFileContent.Add($newHostFileEntry) > $null
}

Out-File -Encoding UTF8 -FilePath $hostFilePath -InputObject $newHostFileContent -Append:$false -Confirm:$false

相关内容