How to create a Run As Administrator shortcut using Powershell
http://stackoverflow.com/questions/28997799/how-to-create-a-run-as-administrator-shortcut-using-powershell
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我们的 powershell 创建 set-shortcut 脚本
# http://poshcode.org/906
Function Set-ShortCut([string]$SourceExe, [string]$TargetFileName='', [string]$Arguments='', [string]$WindowStyle='Normal')
{
If( (Test-Path $SourceExe) -eq $false)
{
Error "$SourceExe doesn't exist";
return
}
Info("Creating desktop shortcut for $SourceExe");
$WshShell = New-Object -comObject WScript.Shell
$BaseName = [System.IO.Path]::GetFileNameWithoutExtension($SourceExe)
$Desktop = [Environment]::GetFolderPath("Desktop")
if($TargetFileName -eq '')
{
$DestinationPath = "$Desktop\$BaseName.lnk"
}
else
{
$DestinationPath = "$Desktop\$TargetFileName.lnk"
}
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $Arguments
if($WindowStyle -is [string]) {
if( $WindowStyle -like "Normal" ) { $WindowStyle = 1 }
if( $WindowStyle -like "Maximized" ) { $WindowStyle = 3 }
if( $WindowStyle -like "Minimized" ) { $WindowStyle = 7 }
}
if( $WindowStyle -ne 1 -and $WindowStyle -ne 3 -and $WindowStyle -ne 7) { $WindowStyle = 1 }
$Shortcut.WindowStyle = $WindowStyle
$Shortcut.Save()
#Allen: 20161114: in Windows 2012, while creating a shortcut, must set the flag to "Run as administrator". Otherwise, will be blocked for execution after invoke
$bytes = [System.IO.File]::ReadAllBytes($DestinationPath)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON
[System.IO.File]::WriteAllBytes($DestinationPath, $bytes)
}
浙公网安备 33010602011771号