• Home
  • About

Automate Python Scripts in PowerShell with Absolute Paths

Programming
Programming/Python
Tools & Platforms
Tools & Platforms/PowerShell
Published

November 4, 2025

Introduction

This post demonstrates how a simple Python script can be automated with PowerShell on Windows.
As a simple test project, the automation performs a trivial task: creating a timestamped log file every minute.

1. Create the project folder structure

All project files are organized under the directory C:\projects\automate_python_with_powershell_abs. The folder structure can be created automatically by running the following Python script.
This script creates the main project directory and its subfolders (scripts, powershell, logs), reports which ones already exist, and lists the current contents of the base directory.

import os

# define the base directory for the project
base_dir = r"C:\projects\automate_python_with_powershell_abs"

# define subfolders for organization
folders = ["scripts", "powershell", "logs"]

# create the folders and report their status
for folder in folders:
    path = os.path.join(base_dir, folder)
    if not os.path.exists(path):
        os.makedirs(path)
        print(f"created: {path}")
    else:
        print(f"already exists: {path}")

print("\nproject folder structure is ready.\n")

# list the current contents of the base directory
print("folders:", os.listdir(base_dir))
already exists: C:\projects\automate_python_with_powershell_abs\scripts
already exists: C:\projects\automate_python_with_powershell_abs\powershell
already exists: C:\projects\automate_python_with_powershell_abs\logs

project folder structure is ready.

folders: ['logs', 'powershell', 'scripts']

2. The Python script

A simple Python script is used to create a timestamped log file each time it is executed.
The script can be saved as: C:\projects\automate_python_with_powershell_abs\scripts\create_log_file_absolute.py
Each execution of this script generates a new log file in the logs directory, named according to the current timestamp.

# create_log_file_absolute.py
from datetime import datetime
import os

# define absolute log directory path
log_dir = r"C:\projects\automate_python_with_powershell_abs\logs"

# generate a timestamped log file name
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
file_name = f"log_{timestamp}.txt"
file_path = os.path.join(log_dir, file_name)

# create the empty log file
open(file_path, "x").close()

# print confirmation
print(f"Log file created: {file_path}")

3. The PowerShell automation script

A PowerShell script is used to run the Python file automatically every 60 seconds.
It can be saved as: C:\projects\automate_python_with_powershell_abs\powershell\run_automation_minute_absolute.ps1

This PowerShell script continuously executes the Python file, waits 60 seconds, and then repeats the process.
It serves as the automation layer that schedules and triggers the Python script.

# change the current working directory to the project folder
Set-Location "C:\projects\automate_python_with_powershell_abs"

# run the Python executable, call the log file script and wait 60 seconds before repeating
while ($true) {
    & "C:\Python312\python.exe" "C:\projects\automate_python_with_powershell_abs\scripts\create_log_file_absolute_path.py"
    Start-Sleep -Seconds 60
}

4. Run the automation

The automation can be started from PowerShell using the following command:

powershell -File "C:\projects\automate_python_with_powershell_abs\powershell\run_automation_minute_absolute.ps1"

Alternatively, it can be launched in a minimized PowerShell window:

Start-Process powershell -WindowStyle Minimized -ArgumentList '-File "C:\projects\automate_python_with_powershell_abs\powershell\run_automation_minute_absolute.ps1"'

Once started, a new log file is created every minute inside the logs folder.

5. Verifying the output files

After the automation had been running for a couple of minutes and was stopped, the logs folder can be checked using the Python code below to view the files that were automatically created.

import os
print("Log files in the 'logs' folder:\n", os.listdir(r"C:\projects\automate_python_with_powershell_abs\logs"))

# alternatives:
# print(*os.listdir(r"C:\projects\automate_python_with_powershell_abs\logs"), sep="\n")
# print(", ".join(os.listdir(r"C:\projects\automate_python_with_powershell_abs\logs")))

6. Stopping the automation

The PowerShell script runs continuously in an infinite loop.
To stop it, several methods can be used depending on how the automation was started:

  • Manual stop: If the script is running in the same PowerShell window, it can be stopped with Ctrl + C, or by closing the window entirely.

  • Find and stop by script name: If the automation was started in a new (minimized or hidden) PowerShell window, the background process running the script can be terminated from another PowerShell session using:

    # Get a detailed list of all running processes (includes CommandLine info)
    Get-CimInstance Win32_Process |
    
    # Filter to include only those where the command line mentions our PowerShell script
    Where-Object { $_.CommandLine -like "*run_automation_minute_absolute.ps1*" } |
    
    # For each matching process, stop it using its process ID
    ForEach-Object { Stop-Process -Id $_.ProcessId -Force }

7. Cleaning up the project directory (optional)

The entire project directory, including its subfolders, can be removed either from Python or directly from PowerShell. This is useful when resetting or repeating the setup during testing.

Option 1 – Delete with Python

import shutil # provides high-level file and folder operations not available in os

if os.path.exists(base_dir):
    shutil.rmtree(base_dir)
    print(f"Deleted: {base_dir}")
else:
    print("Directory not found.")

This Python snippet removes the entire folder structure recursively, including all subdirectories and files inside automate_python_with_powershell_abs. The action is permanent and cannot be undone.

Option 2 – Delete with PowerShell

This single PowerShell command performs the same cleanup, removing all files and folders within the project directory silently.

Remove-Item "C:\projects\automate_python_with_powershell_abs" -Recurse -Force

8. Summary

In this example, a simple automation setup was demonstrated using PowerShell and Python.
A separate post will cover the same workflow using relative paths.

Built with Quarto and Netlify