从 PowerShell 中编辑 hosts 文件

从 PowerShell 中编辑 hosts 文件

我需要能够使用 PowerShell 脚本管理我的环境。我需要定期更改主机文件。但是,每当我尝试从脚本编辑主机时,都会出现以下错误:

Access to the path C:\windows\system32\drivers\etc\hosts is denied

目前我的脚本如下所示:

Function ManageHosts([string] $environment)
{
cd C:\windows\system32\drivers\etc
if($environment.StartsWith("p"))
{
get-content .\hosts.prod | set-content .\hosts -force
}
else
{
get-content .\hosts.dev | set-content .\hosts -force
}
}

答案1

这是权限问题。如果您是本地机器的管理员,我可以提供帮助。
尝试以下操作:右键单击 Powershell 图标并选择以管理员身份运行。然后尝试运行你的脚本;它会起作用。

但是,这并没有回答如何在脚本中执行此操作。您可以在脚本中添加一些代码,这些代码会自动尝试提升 PS 会话的权限,但您仍然必须与每次尝试以管理员身份运行 Vista 或更高版本的某些内容时显示的安全对话框进行交互。因此,不确定这比以管理员身份启动会话是否容易,但请将其添加到脚本的开头:

$WindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$WindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($WindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($WindowsPrincipal.IsInRole($adminRole))
{
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
}
else
{
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
exit

答案2

您需要以管理员权限运行此脚本。只需以管理员身份打开 PowerShell ISE 即可运行。

如果您希望自动运行脚本,则需要将其作为启动脚本运行,或使用 psexec 以系统或管理员身份执行,或创建计划任务。

相关内容