Run single line as Admin in script


Question two of the day! (Can you tell I’m facing a deadline?)

So I have a script that can run without elevation, however there is one line I need to run as an admin.

Is there a way I can do this without running the entire script (or Powershell ISE) as admin?

Yes, you can use Start-Process as described in this StackOverflow discussion. Note that by default this uses the credentials of the user executing the script, so it won’t work for normal users. It either has to be executed by an administrator, or administrator credentials must be supplied with the -Credential parameter.

you can’t run only a line as admin, but you can execute it in a new process with elevated privilege using -Verb parameter.

Start-Process PowerShell -ArgumentList "-C &{code requires elevation}" -Verb RunAs