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

Mic*_*lle 15 windows powershell command-line administrator desktop-shortcut

在我的PowerShell脚本中,我创建了一个.exe的快捷方式(使用与此问题的答案类似的东西):

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()
Run Code Online (Sandbox Code Playgroud)

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

Jan*_*lka 30

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

简而言之,您需要以字节数组的形式读取.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)
Run Code Online (Sandbox Code Playgroud)

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

  • 字节的更改是一些旧式Windows的重要特点。感谢您的PowerShell翻译。 (2认同)
  • PowerShell 数组从第 0 项开始,因此它是第 22 个字节,更准确地说是 ShellLinkHeader 结构的 LinkFlags 结构中的第 2 个字节的第 6 位,即 LinkFlags 结构的第 14 位,使我们到达记录的位置 N“RunAsUser”。但在 64 位 Windows 上,修改的是第 43 个字节的第 6 位。我的猜测是每个字节存储在 16 位而不是 8 位上,为 8 个第一个标志保留的空间现在加倍,因此 RunAsUser 的标志位于字节 4*2 + 16*2 + 1*2 + 1 = 43 .而且由于字节 42 似乎不是 0x00,我怀疑 W64 使用新的未记录标志... (2认同)