Managing Shortcut Files (Part 3)

by Jul 28, 2021

In the previous tip we created new shortcut files, and you have seen how the CreateShortcut() method provides methods to control almost any detail of a shortcut. Here’s the code again that creates a PowerShell shortcut on your Desktop:

$path = [Environment]::GetFolderPath('Desktop') | Join-Path -ChildPath 'myLink.lnk'
$scut = (New-Object -ComObject WScript.Shell).CreateShortcut($path)
$scut.TargetPath = 'powershell.exe'
$scut.IconLocation = 'powershell.exe,0'

One thing the code cannot do, though, is to enable the Administrator privileges of the shortcut file so double-clicking the shortcut icon would automatically elevate the PowerShell that the LNK file launches.

To enable Admin privileges, you’d have to right-click the newly created shortcut file and manually choose “Properties”, then check the appropriate dialog box manually.

Or, you’d need to know the binary format of URL files, and flip the bits via PowerShell. The code below turns the shortcut file that you just created on your desktop into one that automatically elevates:

# launch LNK file as Administrator
# THIS PATH MUST EXIST (use previous script to create the LNK file or create one manually)
$path = [Environment]::GetFolderPath('Desktop') | Join-Path -ChildPath 'myLink.lnk'
# read LNK file as bytes...
$bytes = [System.IO.File]::ReadAllBytes($path)
# flip a bit in byte 21 (0x15)
$bytes[0x15] = $bytes[0x15] -bor 0x20 
# update the bytes
[System.IO.File]::WriteAllBytes($path, $bytes) 

When you now double-click the LNK file, it automatically elevates you. Flip the bit back into place to remove the Admin privilege feature from any LNK file:

$bytes[0x15] = $bytes[0x15] -band -not 0x20 

Twitter This Tip! ReTweet this Tip!