Skip to content

Instantly share code, notes, and snippets.

@peetrike
Last active March 24, 2021 20:23
Show Gist options
  • Save peetrike/5d60d1b76ef47f3fe21d45b61cde60f6 to your computer and use it in GitHub Desktop.
Save peetrike/5d60d1b76ef47f3fe21d45b61cde60f6 to your computer and use it in GitHub Desktop.
Starts given PowerShell commands in elevated Powershell process
#Requires -version 2.0
function Start-AsAdmin {
<#
.Synopsis
Starts given PowerShell commands in elevated Powershell
.Description
Runs given Powershell commands in elevated environment.
.Parameter Command
Powershell commands that require elevated environment
.Parameter WindowStyle
Makes elevated Powershell window visible or hidden
.Example
PS c:\> Start-AsAdmin -Command "Update-Help"
#>
param (
[Parameter(
Mandatory=$true,
HelpMessage='Powershell commands to be started as admin'
)]
[ValidateNotNullorEmpty()]
[String]
$Command
, [ValidateSet('Normal', 'Hidden')]
[Diagnostics.ProcessWindowStyle]
$WindowStyle = 'Hidden'
)
$commandBytes = [Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($commandBytes)
Start-Process -Verb RunAs -FilePath powershell.exe -ArgumentList "-ExecutionPolicy RemoteSigned -encodedcommand $encodedCommand" -Wait -WindowStyle $WindowStyle
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment