tl;dr
The only way to get a remote PowerShell session to execute elevated (with admin privileges) is to connect with a user account (either implicitly or via -Credential
) that has admin privileges on the target machine.
With such an account, the session automatically and invariably runs elevated.
The Invoke-Command
's -RunAsAdministrator
switch can only be used with (virtualization) containers (-ContainerId
parameter), not regular remoting (-ComputerName
parameter).
You cannot elevate on demand in a remote session (the way you can locally, interactively with Start-Process -Verb RunAs
).[1]
Instead, you must make sure that the credentials you're passing to Invoke-Command -Credential
to connect to the remote machine with refer to a user account that (also) has administrative privileges on the target machine, in which case the remote session automatically and invariably runs elevated (with admin privileges).[2]
If you cannot pass such credentials, I think you're out of luck.
To test if the current user has administrative privileges:
# Returns $true if elevated, otherwise $false.
[Security.Principal.WindowsPrincipal]::new(
[Security.Principal.WindowsIdentity]::GetCurrent()
).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
Separately, here's a simple test you can run from inside a session to determine whether it is running with elevation:
# Returns $true if elevated, otherwise $false.
[bool] (net session 2>$null)
[1] Unless the session at already is elevated, -Verb RunAs
presents a pop-up UAC dialog that a user must confirm interactively, which is not supported in a remote session.
[2] The same applies if you use "loopback remoting", i.e. if you target the local machine via remoting, using Invoke-Command -ComputerName .
, for instance, with additional restrictions, however: You cannot use a user that is authorized for remoting but isn't part of the local Administrators
group, and if you use the current user (whether or not with explicit credentials), the calling session must itself be elevated.
Invoke-Command
against the local computer also results in automatic elevation of the commands inside the script block, provided the account has administrative privileges. – Punish