How to create Run As Administrator shortcut using Powershell

In my PowerShell script, I create a shortcut for .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 a shortcut, how do I add to the script so that it runs by default as an administrator?

+14
command-line windows powershell administrator desktop-shortcut
Mar 11 '15 at 21:33
source share
1 answer

This answer is a PowerShell translation of an excellent answer to this question How can I use JScript to create a shortcut using "Run as administrator", etc.

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

In your code, it will 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 someone wants to change something else in the .LNK file, you can refer to the official Microsoft documentation .

+29
Mar 12 '15 at 5:03
source share



All Articles