Run powershell script as Administrator at startup (Windows10)

  • Run with Task Scheduler open highest privileges
  • *.ps1 can't run directly, need extra command file *.cmd

Case

  • My files locate in C:\Users\jiang\Documents
  • My script is used to export WSL2 ports to LAN.

Create powershell script

wsl2-export-ports.ps1

Create command file to running ps1

wsl2-export-ports.cmd

Add task in Task Scheduler

Create Basic Task

Task Scheduler -> Create Basic Task…

  • Name: Wsl2ExportPorts
  • When: When I log on
  • Action: Start a program
  • Program/script: C:\Users\jiang\Documents\wsl2-export-ports.cmd

With the administrator privileges

  • Find Wsl2ExportPorts in Task Scheduler Library
  • Check Run with highest privileges on Tab General of Wsl2ExportPorts dialog
  • Click OK
  • Right Click -> Run
  • You can see the log in wsl2-export-ports.txt.

Restart computer

Test if it works after next restart computer.