I am trying to run Notepad as admin so I can edit my hosts file from the command line.
I have tried
runas /user:(myusername)administrator "notepad c:windowssystem32driversetchosts"
I then input my password and I get
RUNAS ERROR: Unable to run – notepad c:windowssystem32driversetchosts 1327: Account restrictions are preventing this user from signing in. For example: blank pa sswords aren’t allowed, sign-in times are limited, or a policy restriction has been enforc ed.
PS: I know if I give permission to my user account I can edit it without running as admin. But I’d like to know how to do this without having to change permissions on the hosts file.
Solution:
Ok, the reason this doesn’t work is the security model in Windows Vista and newer. An account in the administrators group still runs everything not explicitly elevated as a limited user. The exception is the Administrator
account, which runs everything elevated. For this reason, it is considered generally bad to use as your login account, and is normally disabled.
You could enable it and then runas
to invoke as that account. That introduces a few problems – now you’re running with the environment of a different user, which could have different environment variables set.1
The better way to do this would be actually elevate as your current user via UAC. Unfortunately, the standard command prompt doesn’t include that capability – but both third party programs and the built-in PowerShell and WSHell (VBScript) can do so.
Borrowing from my other answer, you can invoke the PowerShell command directly with powershell -c
:
powershell -c start -verb runas notepad C:WindowsSystem32driversetchosts
which basically tells PowerShell to run the following (start
is aliased to Start-Process
):
Start-Process -Verb "runas" notepad C:WindowsSystem32driversetchosts
The trick here is passing the verb runas
, triggering UAC.
Neither Start-Process -Verb runas
nor the standard cmd runas
will pass the current working directory, so always use the full path in any commands you elevate in this fashion.
Also note that some arguments like -c
may clash with Start-Process
arguments, so the safest way is:
powershell "-c start -verb runas commandname -argumentlist 'arg1 arg2'"
1 Note: this only applies to the user‘s environment variables. Environment variables you set in a parent process are not passed on by UAC! This also applies to runas
, and it’s even worse there because you won’t even get the correct user’s vars.