Automate Windows to Shutdown at a Specific Time by using Python and Task Scheduler

Automate Windows to Shutdown at a Specific Time by using Python and Task Scheduler

Overview

This short article will demonstrate how to automate a Python script to shut down a Windows computer at a specific time by using Task Scheduler.

Materials

  • Windows Computer

  • Python

  • Command Prompt or Terminal

  • Task Scheduler - A program on Windows that gives the option to run scripts at a certain time. It can run the script to shut down our computer at a specific time.

Python Script to Shut Down Computer

Below is the Python Script called "shutdown.py" to shut down a computer:

#!/usr/bin/env python3
# shutdown.py

import os

os.system('shutdown -s')

The shebang "#!/usr/bin/env python3" tells the file it will execute a Python3 script. The module os or operating system was imported to run Windows commands. One command is needed to shut down a Windows computer and it is "shutdown -s".

Running the Shutdown Script

To run the script, write in the terminal "python shutdown.py"

If the script works, then a notification down below will appear:

In a few seconds, the computer will shut down, to prevent that, use the command "shutdown -a" to stop the computer from shutting down.

shutdown -a

By using the command "shutdown -a", a notification similar to below would appear to show the scheduled shutdown has been canceled:

Automating the Shutdown Script

Open Task Scheduler, and from the "Actions" menu, select Create Task:

When creating a task in the "General Menu" give a name and select other preferences to run the script:

In "Triggers", select "New"

Customize the script to run one time, daily, weekly or monthly

In "Actions", select "New"

Under "Program/script", put the file location of python.exe. To add arguments, put the name of the shutdown script. For Start in, put the file location of the Python file.

If a Python script needs to be run, the Python.exe program needs to be run first to successfully execute any instructed Python scripts afterward. "Program/Script" takes priority to be run first, which is why it needs to be instructed to run Python.exe. An argument is telling what and the name of the script that needs to be run, and in this case, it is being told to run the shutdown.py file. "Start in" takes in a file directory, to search for the file that was told to run in "Add arguments".

Under conditions, all the options can be unchecked for the script to run either on battery or AC power.

After configuring these customizations, select OK and the shutdown.py script should run at the time that it was configured.

Source Code

https://github.com/AndrewDass1/SCRIPTS/tree/main/Windows/Python/Automation%20and%20Shutdown