powershell - 如何通过powershell命令删除主机条目
问题描述
我尝试在主机文件中添加条目,如下所示,需要帮助从主机文件中删除相同的条目。
Add-Content -Path C:\Windows\System32\drivers\etc\hosts -Value 20.0.0.1`tlocalhost -Force
解决方案
我 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".
#>
添加与删除更难,我不太同意。因为它只是一个文本文件,一个重要的,但只是一个文本文件......
- 正常读取文件
- 选择带有目标字符串模式的整行
- 删除该行
- 创建要添加的新行
- 附加该行。
..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
推荐阅读
- python - Python-具有条件的函数中的Numpy数组
- javascript - Flexbox 下拉子菜单
- c# - 为什么 typeof(Child<>).BaseType.IsGenericTypeDefinition 为假?
- android - Android - Espresso - 当列表中存在其他对象时断言对象
- java - Java不同的引用类型和类对象
- php - phpMailer IMAP 编码/解码
- database - 访问中具有自动编号和日期字段的最大聚合函数
- java - 如何将HashMap中的键添加到Java中具有相同顺序的列表中
- java - Ripple XRP Ledger - 无法验证交易(测试网)
- javascript - 无法解决 javascript 中的内部承诺