windows – 如何使用Powershell创建Run As Administrator快捷方式

在我的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.

相关文章

Windows2012R2备用域控搭建 前置操作 域控主域控的主dns:自...
主域控角色迁移和夺取(转载) 转载自:http://yupeizhi.blo...
Windows2012R2 NTP时间同步 Windows2012R2里没有了internet时...
Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...