Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
get-content .\ | set-content .\hosts -force
get-content .\ | set-content .\hosts -force
share|improve this question
Is the problem the fact you'll need to run that as an administrator? – FreudianSlip Aug 13 '13 at 16:02
I thought that the -force switch was basically the same thing as running as an administrator :/ – David Rett Aug 13 '13 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 '13 at 16:37
up vote 6 down vote accepted

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:

$WindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($WindowsID)
if ($WindowsPrincipal.IsInRole($adminRole))
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$newProcess.Verb = "runas";
share|improve this answer

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.