Skip to content

Instantly share code, notes, and snippets.

@nigilan
Created September 26, 2017 15:11
Show Gist options
  • Save nigilan/452864a60efdb5760dfa19b9fa853529 to your computer and use it in GitHub Desktop.
Save nigilan/452864a60efdb5760dfa19b9fa853529 to your computer and use it in GitHub Desktop.
This piece of code is to run commands in powershell as administrator.
Set-ExecutionPolicy Unrestricted -Scope CurrentUser -Force
# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;
# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running as an administrator, so change the title and background colour to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
$Host.UI.RawUI.BackgroundColor = "DarkBlue";
Clear-Host;
}
else {
# We are not running as an administrator, so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
Exit;
}
# You can replace below lines with your code
# npm install -g npm-windows-upgrade
# npm-windows-upgrade -p -v latest
# npm install -g node-gyp@latest
# npm config set msvs_version 2015 –global
# npm install --global windows-build-tools
Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
@nigilan
Copy link
Author

nigilan commented Sep 26, 2017

Code from msdn blog. This may not execute some command that needs Execution policy Unrestricted. Hence adding that line in the beginning!

@jgangso
Copy link

jgangso commented Jul 4, 2022

Nice one. Useful that it leaves the shell open so one can see eventual error messages

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment