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 .\hosts.prod | set-content .\hosts -force
get-content .\hosts.dev | set-content .\hosts -force
  • Is the problem the fact you'll need to run that as an administrator? 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

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";

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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