且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 Powershell 创建以管理员身份运行的快捷方式

更新时间:2023-02-03 20:39:51

这个答案是这个问题的一个优秀答案的 PowerShell 翻译如何使用JScript 创建使用以管理员身份运行"的快捷方式.

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".

简而言之,您需要以字节数组的形式读取 .lnk 文件.定位字节 21 (0x15) 并将位 6 (0x20) 更改为 1.这是 RunAsAdministrator 标志.然后将字节数组写回 .lnk 文件.

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("$HomeDesktopColorPix.lnk")
$Shortcut.TargetPath = "C:Program Files (x86)ColorPixColorPix.exe"
$Shortcut.Save()

$bytes = [System.IO.File]::ReadAllBytes("$HomeDesktopColorPix.lnk")
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON
[System.IO.File]::WriteAllBytes("$HomeDesktopColorPix.lnk", $bytes)

如果有人想更改 .LNK 文件中的其他内容,您可以参考 微软官方文档.

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