如何使用 Powershell 创建 运行 As Administrator 快捷方式

How to create a Run As Administrator shortcut using Powershell

在我的 PowerShell 脚本中,我创建了一个 .exe 的快捷方式(使用类似于 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()

现在,当我创建快捷方式时,如何添加到脚本中以使其默认为 运行 管理员?

这个答案是对这个问题的一个很好的答案的 PowerShell 翻译 How can I use JScript to create a shortcut that uses "Run as Administrator".

简而言之,您需要将.lnk 文件作为字节数组读入。找到字节 21 (0x15) 并将位 6 (0x20) 更改为 1。这是 RunAsAdministrator 标志。然后将字节数组写回 .lnk 文件。

在您的代码中,它看起来像这样:

$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)

如果有人想更改 .LNK 文件中的其他内容,您可以参考 official Microsoft documentation

您可以为此使用 -Elevate true 开关:

    CreateShortcut -name "myApp" -Target 
    "${env:ProgramFiles}\mApp\myApp.exe" -OutputDirectory 
    "C:\Users\Public\Desktop" -Elevated True