web-dev-qa-db-fra.com

Comment créer un raccourci Exécuter en tant qu'administrateur à l'aide de Powershell

Dans mon script PowerShell, je crée un raccourci vers un .exe (en utilisant quelque chose de similaire à la réponse de cette 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()

Maintenant, quand je crée le raccourci, comment puis-je ajouter au script pour le rendre par défaut à l'exécution en tant qu'administrateur?

19
Michelle

Cette réponse est une traduction PowerShell d'une excellente réponse à cette question Comment puis-je utiliser JScript pour créer un raccourci qui utilise "Exécuter en tant qu'administrateur" .

En bref, vous devez lire le fichier .lnk dans un tableau d'octets. Localisez l'octet 21 (0x15) et remplacez le bit 6 (0x20) par 1. Il s'agit de l'indicateur RunAsAdministrator. Ensuite, vous réécrivez votre tableau d'octets dans le fichier .lnk.

Dans votre code, cela ressemblerait à ceci:

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

Si quelqu'un veut changer autre chose dans un .LNK fichier auquel vous pouvez vous référer documentation officielle Microsoft .

34
Jan Chrbolka