Powershell 操作主机文件 [英] Powershell to manipulate host file

查看:25
本文介绍了Powershell 操作主机文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看是否可以创建 powershell 脚本来更新主机文件中的内容.

I am looking at to see if I can create powershell script to update the contents in the host file.

有人知道是否有任何示例使用 powershell 或任何其他脚本语言来操作主机文件?

Anybody know if there are any examples that manipulate the host file using powershell or any other scripting lanaguages?

谢谢.

推荐答案

首先,如果您使用的是 Vista 或 Windows 7,请确保从提升的提示符处运行这些命令:

First up, if you're on Vista or Windows 7 make sure you run these commands from an elevated prompt:

# Uncomment lines with localhost on them:
$hostsPath = "$env:windir\System32\drivers\etc\hosts"
$hosts = get-content $hostsPath
$hosts = $hosts | Foreach {if ($_ -match '^\s*#\s*(.*?\d{1,3}.*?localhost.*)')
                           {$matches[1]} else {$_}}
$hosts | Out-File $hostsPath -enc ascii

# Comment lines with localhost on them:
$hosts = get-content $hostsPath
$hosts | Foreach {if ($_ -match '^\s*([^#].*?\d{1,3}.*?localhost.*)') 
                  {"# " + $matches[1]} else {$_}} |
         Out-File $hostsPath -enc ascii

鉴于此,我认为您可以了解如何根据需要使用正则表达式来操作条目.

Given this I think you can see how to use a regex to manipulate entries as necessary.

这篇关于Powershell 操作主机文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆