Introduction
Many PowerShell scripts require administrative privileges to execute certain commands. Without proper elevation, these scripts can fail with permission errors. By adding a specific directive to your script, you can ensure it always runs with the necessary permissions.
Forcing Script Execution as Administrator
To force a script to run as an administrator, add the following line at the beginning of your PowerShell script:
#Requires -RunAsAdministrator
This directive ensures that the script will only run if executed with administrative privileges. If the script is not run as an administrator, it will return an error message.
Example Script
Here is an example of a script that requires administrative privileges:
#Requires -RunAsAdministrator
# Sample script content
Write-Host "This script is running with administrative privileges."
If the script is not run as an administrator, you will see the following error message:
.\TypeLog.ps1 : Impossible d’exécuter le script «TypeLog.ps1», car il contient une instruction «#requires» pour une
exécution en tant qu’administrateur. La session Windows PowerShell actuelle n’est pas exécutée en tant
qu’administrateur. Démarrer Windows PowerShell à l’aide de l’option Exécuter en tant qu’administrateur, puis essayez
de réexécuter le script.
Au caractère Ligne:1 : 1
+ .\TypeLog.ps1
+ ~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (TypeLog.ps1:String) [], ScriptRequiresException
+ FullyQualifiedErrorId : ScriptRequiresElevation
0 Comments