Advertisement
tetratheta

[Windows] Register itself to Task Scheduler with admin privileges

Jan 4th, 2024 (edited)
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 1.54 KB | None | 0 0
  1. @echo off
  2. setlocal ENABLEDELAYEDEXPANSION
  3.  
  4. REM Check admin privileges
  5. net session >nul 2>&1
  6. if !ErrorLevel! equ 0 (set "IS_ADMIN=true") else (set "IS_ADMIN=false")
  7.  
  8. if "%1" == "TASKRUN" (
  9.   if "!IS_ADMIN!" == "true" (
  10.    REM Run script
  11.    REM ====================
  12.    REM Put your commands in here. They will run with admin privileges.
  13.    REM ====================
  14.    REM ===== EXAMPLE ======
  15.    REM cd /d "E:\Program Files\Hotta\WmGpLaunch\"
  16.    REM start "First" "E:\Program Files\Hotta\WmGpLaunch\WmgpLauncher.exe"
  17.   ) else (
  18.     mshta vbscript:Execute^("msgbox ""This task requires admin privileges"",0,""Error"":close"^)
  19.   )
  20. ) else (
  21.   set "TNAME=SkipUAC\%~n0"
  22.   schtasks /query /tn "!TNAME!" >nul 2>&1
  23.   if !ErrorLevel! equ 0 (
  24.    REM Task exists. Run it.
  25.     echo Task detected. Running it...
  26.     schtasks /run /tn "!TNAME!"
  27.   ) else (
  28.    REM Task doesn't exists. Create it.
  29.     echo Task is not detected. Creating new one...
  30.    REM Task creation needs admin privileges
  31.     if not "!IS_ADMIN!" == "true" (goto ELEVATE)
  32.     schtasks /create /f /tn "!TNAME!" /sc ONCE /st "23:59" /tr "\"%~dpnx0\" TASKRUN" /rl HIGHEST
  33.     if !ErrorLevel! equ 0 (
  34.      REM Run newly created task
  35.       schtasks /run /tn "!TNAME!"
  36.     ) else (
  37.      REM Task creation failed
  38.       mshta vbscript:Execute^("msgbox ""Failed to create task"",0,""Failed"":close"^)
  39.     )
  40.   )
  41. )
  42. goto:eof
  43.  
  44. :ELEVATE
  45. cd /d %~dp0
  46. mshta "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
  47. exit
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement