Author Archives: Kiprono Koech

Running Powershell Script Within Python Script

You can run a PowerShell script in Python using the subprocess or os module. In this article, we will learn how to execute a PowerShell script from Python in Windows, Mac, or Linux. The fundamental prerequisite is to have PowerShell installed on your system.

Windows comes preinstalled with PowerShell (you can update it by downloading the latest version from this link). You can install PowerShell core on Linux and Mac using the information below.

Installing PowerShell core in Linux

You can install PowerShell core on Debian by running the following commands from the terminal (source: Microsoft website). If you are running a different distribution, you can get the installation commands from here.

Installing PowerShell Core on Mac

You can install PowerShell using Homebrew by running the following command on the terminal.

Or update it using the commands

Once done with the installation, you can start PowerShell from Windows, Linux, or Mac terminal by running this command in the terminal

And execute a PowerShell script using the command

At this point, we are ready to execute a PowerShell script from within a Python script.

Running PowerShell Script Within Python Script

As an example, we will execute the PowerShell script named script1.ps1 with the content below. The script accepts one parameter, $Name, and prints a greeting message to the console based on the time of the day.

Output:

The time is 04/14/2023 18:46:50
Good afternoon, Decker!

If you want to save the output of the PowerShell script to a variable, you can send the output to the subprocess.PIPE, as shown below.

Output:

The time is 04/15/2023 17:37:35
Good afternoon, Decker!

You can also run the PowerShell script using the os module as follows.

If the execution runs successfully with no error, return_code=0. Note that os. system() has limited functionalities. The subprocess module discussed above provides more facilities for spawning new processes.

Conclusion

This guide discussed using the subprocess module to run the PowerShell script using Python across different platforms – Windows, Linux, and Mac.