Skip to content

Instantly share code, notes, and snippets.

@BlueDrink9
Created May 3, 2024 01:22
Show Gist options
  • Save BlueDrink9/b3b6c162c3ea43f7b29cbed117fe7b69 to your computer and use it in GitHub Desktop.
Save BlueDrink9/b3b6c162c3ea43f7b29cbed117fe7b69 to your computer and use it in GitHub Desktop.
Run file as regular user with admin permissions, once set up by an administrator once.
# Create a scheduled task that runs the specified python script as admin, without
# needing an admin password. Ensure that the script is in a write-protected folder.
$python_path = "C:\Python311\python.exe"
$script_path = "C:\test\test.py"
$task_folder = "\"
$task_name = "RunServerReviewScript"
$shortcut_batch_script_path = "C:\" $task_name ".bat"
$admin_user = "$env:USERNAME" # change as necessary
# Create the task
$action = New-ScheduledTaskAction -Execute $python_path -Argument $script_path
$principal = New-ScheduledTaskPrincipal -UserId $admin_user -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RunOnlyIfLoggedOn $false
$description = "Scheduled task to run the server review Python script with admin privileges. Running this manually as a regular user will run the review script with admin privileges"
Register-ScheduledTask -Action $action -TaskName $task_name -Principal $principal -Settings $settings
# Modify security permissions on the task so that it can be read and executed (but not edited) by non-admin users
$Scheduler = New-Object -ComObject "Schedule.Service"
$Scheduler.Connect()
$GetTask = $Scheduler.GetFolder($task_folder).GetTask($task_name)
$GetSecurityDescriptor = $GetTask.GetSecurityDescriptor(0xF)
Write-Host "Previous security settings: " (ConvertFrom-SddlString $GetSecurityDescriptor).DiscretionaryAcl
if ($GetSecurityDescriptor -notmatch 'A;;0x1200a9;;;AU') {
$GetSecurityDescriptor = $GetSecurityDescriptor + '(A;;GRGX;;;AU)'
$GetTask.SetSecurityDescriptor($GetSecurityDescriptor, 0)
}
Write-Host "New security settings: " (ConvertFrom-SddlString $GetSecurityDescriptor).DiscretionaryAcl
printf "\n"
# Create a .bat script to run the scheduled task (mainly for convenience)
$batch_script_content = @"
@echo off
schtasks /run /tn "$task_name"
"@
$batch_script_content | Set-Content -Path $shortcut_batch_script_path
Write-Host "Batch script to run the script as admin been created at: $shortcut_batch_script_path"
# Provide instructions for modifying the scheduled task to run whether the user (admin) is logged in or not
Write-Host "Now you need to manually alter scheduled task '$task_name' to run whether the user (admin) is logged in or not"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment