【问题标题】:How to create a Run As Administrator shortcut using Powershell如何使用 Powershell 创建以管理员身份运行的快捷方式
【发布时间】:2015-05-13 21:39:43
【问题描述】:

在我的 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()

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

【问题讨论】:

  • 一定要阅读上面链接的问题 Nathan。要将代码转换为 PowerShell: $file = "$Home\Desktop\ColorPix.lnk"; $bytes = [System.IO.File]::ReadAllBytes($file); $bytes[0x15] = $bytes[0x15] -bor 0x20; #Set RunAsAdministrator [System.IO.File]::WriteAllBytes($file, $bytes);使用 –bor 设置 RunAsAdministrator 选项,使用 –bxor 取消设置。

标签: windows powershell command-line administrator desktop-shortcut


【解决方案1】:

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

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

【讨论】:

  • 这是一个答案还是一个问题? CreateShortcut 是什么?
【解决方案2】:

这个答案是这个问题的优秀答案的 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

【讨论】:

  • 那个字节变化是一些老式的 Windows 骗局。感谢 PowerShell 翻译。
  • 最后一行对我不起作用,所以我改用$bytes | Set-Content $shortcutPath -Encoding Byte
  • 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 使用新的未记录标志...
  • @hsimah 不管字节变化是好是坏,它与Windows无关。
  • @g.pickardou 我不知道其他平台上存在字节;感谢您抽出时间来分享您丰富的知识
猜你喜欢
  • 1970-01-01
  • 2021-05-27
  • 1970-01-01
  • 2012-06-25
  • 2016-08-31
  • 2011-05-07
  • 1970-01-01
  • 2014-09-27
  • 2011-11-15
相关资源
最近更新 更多