4

I need to be able to manage my environments using a PowerShell script. I need to change my host file periodically. However, whenever I try to edit the host from my script, I get the following error:

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

Currently my script looks like this:

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
}
}
3
  • Is the problem the fact you'll need to run that as an administrator? Aug 13, 2013 at 16:02
  • I thought that the -force switch was basically the same thing as running as an administrator :/
    – David Rett
    Aug 13, 2013 at 16:22
  • Hi David. Please use the preview below your post to look at how it'll be formatted. You need to indent code by 4 spaces or select it and press Ctrl-K (or the {} button).
    – slhck
    Aug 13, 2013 at 16:37

2 Answers 2

6

This is a question of privileges. If you're an admin on your local box, I can help.
Try this: Right-click your Powershell icon and select Run As Administrator. Then try running your script; it will work.

However, this doesn't answer how you can do this from within a script. You can add some code to your script that will automatically try to make your PS session elevated, but you will still have to interact with the security dialog box that shows up anytime you try and run something as an admin that's Vista or later. So, not sure how much easier this is than just starting your session as an admin, but add this to the beginning of your script:

$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

You need to run this script with administrator privileges. Simply open PowerShell ISE as Administrator and it should run.

If you're looking to automate the running of the script, you'll need to run this as a startup script, or use psexec to execute as System or Administrator, or create a scheduled task.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .