powershell 用于向hosts文件添加/删除/查看条目的Powershell脚本。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 用于向hosts文件添加/删除/查看条目的Powershell脚本。相关的知识,希望对你有一定的参考价值。
#
# Powershell script for adding/removing/showing entries to the hosts file.
#
# Known limitations:
# - does not handle entries with comments afterwards ("<ip> <host> # comment")
#
$file = "C:\Windows\System32\drivers\etc\hosts"
function add-host([string]$filename, [string]$ip, [string]$hostname) {
remove-host $filename $hostname
$ip + "`t`t" + $hostname | Out-File -encoding ASCII -append $filename
}
function remove-host([string]$filename, [string]$hostname) {
$c = Get-Content $filename
$newLines = @()
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
if ($bits[1] -ne $hostname) {
$newLines += $line
}
} else {
$newLines += $line
}
}
# Write file
Clear-Content $filename
foreach ($line in $newLines) {
$line | Out-File -encoding ASCII -append $filename
}
}
function print-hosts([string]$filename) {
$c = Get-Content $filename
foreach ($line in $c) {
$bits = [regex]::Split($line, "\t+")
if ($bits.count -eq 2) {
Write-Host $bits[0] `t`t $bits[1]
}
}
}
try {
if ($args[0] -eq "add") {
if ($args.count -lt 3) {
throw "Not enough arguments for add."
} else {
add-host $file $args[1] $args[2]
}
} elseif ($args[0] -eq "remove") {
if ($args.count -lt 2) {
throw "Not enough arguments for remove."
} else {
remove-host $file $args[1]
}
} elseif ($args[0] -eq "show") {
print-hosts $file
} else {
throw "Invalid operation '" + $args[0] + "' - must be one of 'add', 'remove', 'show'."
}
} catch {
Write-Host $error[0]
Write-Host "`nUsage: hosts add <ip> <hostname>`n hosts remove <hostname>`n hosts show"
}
以上是关于powershell 用于向hosts文件添加/删除/查看条目的Powershell脚本。的主要内容,如果未能解决你的问题,请参考以下文章
从csv读取后使用powershell向vm添加标签时出错
powershell 用于添加上下文菜单项以打开PowerShell命令提示符并使用PowerShell ISE编辑文件的功能
ansible向inventory文件中添加host
如何使用python和powershell向Windows 10添加用户
powershell 向Mac OS Dock添加空白区域
powershell 从https://github.com/StevenBlack/hosts更新Windows主机文件