首页 > 解决方案 > 如何通过powershell命令删除主机条目

问题描述

我尝试在主机文件中添加条目,如下所示,需要帮助从主机文件中删除相同的条目。

Add-Content -Path C:\Windows\System32\drivers\etc\hosts -Value 20.0.0.1`tlocalhost -Force

标签: powershell

解决方案


我 100% 同意在对关键文件进行操作之前始终对其进行复制。

$HostFile = Get-ChildItem -Path 'C:\Windows\System32\drivers\etc\hosts' 
<#
    Directory: C:\Windows\System32\drivers\etc


Mode                LastWriteTime         Length Name                                                                                                         
----                -------------         ------ ----
-a----        18-Mar-19     21:49            824 hosts
#>

Copy-Item -Path $HostFile.FullName -Destination "$($HostFile.DirectoryName)\$($HostFile.Name)_$(Get-Date -Format 'ddMMyyyy@HHmm')" -WhatIf
<#
What if: Performing the operation "Copy File" on target "Item: C:\Windows\System32\drivers\etc\hosts Destination: C:\Windows\System32\drivers\etc\hosts_2102202
0@1602".
#>

添加与删除更难,我不太同意。因为它只是一个文本文件,一个重要的,但只是一个文本文件......

  1. 正常读取文件
  2. 选择带有目标字符串模式的整行
  3. 删除该行
  4. 创建要添加的新行
  5. 附加该行。

..vs 在该行中挑选嵌入的东西。

# Find the line
Get-Content -Path 'C:\Windows\System32\drivers\etc\hosts' | 
Select-String -Pattern '\d.*localhost.*'
<#
#   127.0.0.1       localhost
#   ::1             localhost
#>

# Remove the line
(Get-Content -Path 'C:\Windows\System32\drivers\etc\hosts' | 
Select-String -Pattern '\d.*localhost.*') -replace ''

# Add a line
Add-Content -Path 'C:\Windows\System32\drivers\etc\hosts' -Value '  151.101.193.69       stackoverflow.com'

# Or just this
$HostFile = Get-ChildItem -Path 'C:\Windows\System32\drivers\etc\hosts' 
Copy-Item -Path $HostFile.FullName -Destination "$($HostFile.DirectoryName)\$($HostFile.Name)_$(Get-Date -Format 'ddMMyyyy@HHmm')" 
(Get-Content -Path 'C:\Windows\System32\drivers\etc\hosts' | 
Select-String -Pattern '\d.*localhost.*') -replace '', '    151.101.193.69       stackoverflow.com' 

哦,顺便说一句,这已经存在了一段时间,通过 MS powershellgallery.com,所以除非是学习努力,否则没有必要从头开始。

Find-Module -Name '*hostfile*' | Format-Table -AutoSize

<#
Version Name                Repository Description                                 
------- ----                ---------- -----------                                 
1.0.2   Web.Helper.HostFile PSGallery  Helper to manage the Windows host file      
1.0.3   Add-HostFileEntry   PSGallery  Adds and removes entries from the HOSTS file
1.0     HostFile            PSGallery  Helper commands to interact with host file 
#>

修改添加、删除 - Windows 在本地和远程托管文件 - PowerShell

您可以使用此 PowerShell 脚本修改添加、删除 - Windows 在本地和远程托管文件。该脚本有 4 个部分 #1st 部分是关于添加主机记录,在本地计算机中,或者我们可以通过 gpo 中的 Login 脚本部署。#2nd 部分是修改、替换或删除任何主机条目下载:modifyhost.ps1


推荐阅读