Automate Tasks on Windows 10 with PowerShell and Task Scheduler
Introduction
Recently I had an idea to automate a task that I manually do every day after logging into my machine.
To automate, I use a PowerShell script with Windows Task Scheduler to call it every time I log in on Windows 10. The process is very simple and it works even if the script needs admin rights to run. Let me show you!
Step 1: Create a script that solves your problem
In my case, I always have to restart wsl2 on my Windows machine before open it (god knows why). So I created a file wsl_shutdown.ps1 with the following script on it:
wsl --shutdown ;
exit ;
I know, the script is very simple and it doesn’t need any admin privileges to run. Furthermore, I could have achieved the same solution by just creating a batch script and inserting it over ‘%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup’ directory, right?
Right.
So, why are you doing this? Because I wanted a solution that I could use on every script, even those that require admin privileges to run. For example, I applied the same solution to a script that maps WSL2 ports with the following script:
wsl --shutdown ;netsh interface portproxy reset ;$wsl_ipaddr = wsl -d Ubuntu-20.04 hostname -I ;# the command below needs admin privileges to run
netsh interface portproxy add v4tov4 listenport=3000 listenaddress=127.0.0.1 connectport=3000 connectaddress=$wsl_ipaddr ;netsh interface portproxy show all ;exit ;
Anyway, we already have our wsl_shutdown.ps1 script. You can save it on any directory of your preference, just make sure to never delete it.
Step 2: Create a Task scheduler to execute the script
Now we need to create a Task on our Task Scheduler that will run wsl_shutdown.ps1 every time I log in on my machine. So, let’s follow the process below:
Open Windows Task Scheduler
Create a new Task with the following configurations:
General tab:
- Select Run only when user is logged on
- Check Run with highest privileges
- Set Configure for: Windows 10
Triggers tab:
- Begin the task: At log on
- Check Enabled option
Actions tab:
- Action: Start a program
- Settings > Program/script: powershell
- Add arguments (optional): -noprofile -executionpolicy bypass -file C:\<path to file>\wsl_shutdown.ps1
PS: replace ‘C:\<path to file>’ with the path related to ‘wsl_shutdown.ps1’ script file
Settings tab:
- Make sure Allow task to be run on demand is checked.
Done! Now, every time we log in, our script will be executed.
PS: If for some reason you need to manually execute the script, you can also do it by opening Task Scheduler and running it.
Thanks!
Many thanks! Hope you enjoy! Any feedback would be appreciated!