HOWTO: Run remote powershell script as administrator


Sooner or later, as you begin to hone your PowerShell skills, you’ll start writing scripts to automate repetitive tasks. If you run your workstation with standard user privileges, you’ll soon discover that it’s not possible to launch PowerShell scripts with administrative privileges by right-clicking the script and selecting Run as administrator from the context menu (which is available for most over types of executable). Today I’ll show you two ways that you can run remote powershell script with admin privileges.


1. Modify a Script to Force Elevation:

   - Add this snippet of code to the beginning of your PowerShell script, and a UAC prompt will appear, asking for administrative credentials or consent before any subsequent code is executed.

param([switch]$Elevated)
function Check-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Check-Admin) -eq $false) {
if ($elevated)
{
# could not elevate, quit
}

else {

Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}

2. Run a Code from an Elevated Instance of the Windows PowerShell Integrated Scripting Environment (ISE):

   - Alternatively, you can run scripts directly from inside the Windows PowerShell ISE. To start the ISE with administrative privileges:

Switch to the Start menu in Windows, type powershell ise, and make sure that PowerShell ISE is selected in the search results. Press CTRL+SHIFT+ENTER to start the ISE with elevated privileges and enter administrative credentials or give sent if prompted.
In the PowerShell ISE window, select Open from the File menu to load your script.
Once the script is loaded into the ISE, press F5 to run the script.
The Windows PowerShell ISE is a useful environment for creating and editing your scripts. You have access to all the installed PowerShell modules and their related commands, plus troubleshooting tools.

Also consider using Action1 to run remote powershell script as administrator if:
- You need to perform this action on multiple (hundreds or even thousands) computers simultaneously.
- Some of your endpoints are laptops not connected to corporate network at all times.

Action1 is a cloud-based platform for software deployment, software/hardware inventory, patch management, endpoint configuration and more. It is free with basic functionality.


Other Relevant HOWTOs: