Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Run As Administrator shortcut using Powershell

In my PowerShell script, I create a shortcut to a .exe (using something similar to the answer from this question):

$WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk") $Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe" $Shortcut.Save() 

Now, when I create the shortcut, how do I add to the script to make it default to running as Administrator?

like image 377
Michelle Avatar asked Mar 11 '15 21:03

Michelle


People also ask

How do I run a shortcut as administrator in PowerShell?

Use the Ctrl + Shift + Enter keyboard shortcut and confirm the UAC prompt to run and open PowerShell as an admin.

How do I always run a PowerShell script as administrator?

Use PowerShell in Administrative Mode If you need to run a PowerShell script as an administrator, you will need to open PowerShell in administrative mode. To do so, find PowerShell on the Start menu, right click on the PowerShell icon, and then select More | Run as Administrator from the shortcut menu.


1 Answers

This answer is a PowerShell translation of an excellent answer to this question How can I use JScript to create a shortcut that uses "Run as Administrator".

In short, you need to read the .lnk file in as an array of bytes. Locate byte 21 (0x15) and change bit 6 (0x20) to 1. This is the RunAsAdministrator flag. Then you write you byte array back into the .lnk file.

In your code this would look like this:

$WshShell = New-Object -comObject WScript.Shell $Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk") $Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe" $Shortcut.Save()  $bytes = [System.IO.File]::ReadAllBytes("$Home\Desktop\ColorPix.lnk") $bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON [System.IO.File]::WriteAllBytes("$Home\Desktop\ColorPix.lnk", $bytes) 

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

like image 51
Jan Chrbolka Avatar answered Oct 05 '22 01:10

Jan Chrbolka