Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Run a command with specific user priviledge in Windows (like sudo in Unix)


You can use runas command to run a command with specific user privilege. (Note: You have to type password into command prompt):

C:\>runas /user:domain\username cmd
Enter the password for domain\username:
Attempting to start cmd as user "domain\username" ...

But, you will get error with a command with arguments:

C:\>runas /user:domain\username net start WebClient


RUNAS [ [/noprofile | /profile] [/env] [/savecred | /netonly] ]
        /user:<UserName> program

You can also use Start-Process -Verb runas with the same aim without typing password (UAC dialog will pop up for privileges):

PS > Start-Process -Verb runas cmd

But you will get an error when you want pass arguments to the command:

PS > Start-Process -Verb runas net start WebClient

Start-Process : A positional parameter cannot be found that accepts argument 'WebClient'.
At line:1 char:1
+ Start-Process <<<<  -Verb runas net start WebClient
    + CategoryInfo          : InvalidArgument: (:) [Start-Process]、ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand

Or you will get another error when you quote the command and arguments:

PS > Start-Process -Verb runas "net start WebClient"
Start-Process : This command cannot be executed due to the error: The system ca
nnot find the file specified.
At line:1 char:14
+ Start-Process <<<<  -Verb runas "net start WebClient"
    + CategoryInfo          : InvalidOperation: (:) [Start-Process]、InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand


You should quote the command and arguments in runas command:

C:\>runas /user:domain\username "net start WebClient"
Enter the password for domain\username:
Attempting to start net start WebClient as user "domain\username" ...

You should use -ArgumentList option to pass argument in Start-Process cmdlet:

Start-Process -Verb runas -ArgumentList "stop WebClient" net