What's the best programming language? You might get ten different answers when asking ten different developers. In this article, we're going to compare two languages; PowerShell and Python. You will get a glimpse into each of these languages and understand how they compare and contrast in features such as syntax, availability across platforms, and more.

It's time for a PowerShell vs. Python bout!

By the end of this article, you'll be able to answer some common questions:

  • What do both of these languages have in common?
  • What makes them different?
  • What are the best use cases for each of them?
  • How does the syntax differ?
  • What kind of role would someone have to best leverage one over the other?

This article is for those who have little to no knowledge about either language and are confused about whether to use PowerShell or Python. This article is also for those who already understand one of the languages, and would like to learn about the other.

Let's dive in!

By Job Role

Although you might be able to talk about the technical aspects of Python and PowerShell all day, an important part of comparing the two languages is to determine what kind of job role most suits either language.

Both PowerShell and Python were developed on two sides of a fence (Microsoft and the open source Linux community). Both languages' syntax, community, and therefore, their overall feel are different and thus are generally adopted to certain job roles

It should be noted here, that PowerShell (Core), which in version 6.0.0 and later, has been open-sourced. Times are a changin'.

System Administrators

Both PowerShell and Python are great languages to learn for sysadmins. They are both great automation tools, and can potentially lots of time for a sysadmin. Arguably though, for Windows sysadmins, PowerShell will be a better choice just because of its native .NET framework integration.

Python, on the other hand, is great for Linux sysadmins.

Although Python and PowerShell (Core) are both cross-platform, you'll find that the large majority of job roles out there will be split between Windows and PowerShell, and Python and Linux.

Developers

For more developer-oriented jobs, Python is by far the leader. Python has massive support in areas that PowerShell has never touched, such as data science, statistical analysis, and more. Python feels more like a scientifically-oriented language sometimes.

Python also runs many large server-side web apps and other "developer friendly" applications.

Although PowerShell can be used as a development language, it's typically better suited in job roles that need more automation, like DevOps or general sysadmin automation.

By Operating System

PowerShell

PowerShell is the hero for Windows environments; it’s the best skill you can leverage for automating tasks in Windows. This is especially true when it comes to products like Active Directory and Microsoft Exchange in both on-premises and Office 365 varieties.

Since PowerShell has direct access to the .NET Framework, it’s perfectly integrated with all Windows systems and can easily be used to accomplish any task.

However, PowerShell does have Linux support but, as of this writing, it's not nearly as prevalent as Python.

Python

Python is generally better in Linux environments. Due to its deep roots in the Linux community, you'll find Python modules to do nearly anything in Linux.

Python can also run on other platforms such as iOS and AIX.

By Task

PowerShell

You can use PowerShell to create a tool for administering daily tasks, and you can even create a GUI using Windows PowerShell for your tool to be more user-friendly.

Python

Python is generally best used for "heavier" tasks like machine learning, statistics, data science, and server-side web and desktop applications. Python also has great support for image processing.

Understanding the Syntax Commonalities and Differences

Let's get down to the nuts and bolts of each language to compare and contrast them.

PowerShell and Python are object-oriented, which means both are built on the concept of logical objects where they create, manipulate, and reuse objects to perform specific tasks.

Both PowerShell and Python reuse code by the means of modules. Modules can be potentially reused later in other programs, or you can directly import modules created by other programmers.

Both languages have a large library of modules which you can easily use in your scripts.

PowerShell is task-based command-line shell and scripting language built on top of .NET framework which accepts and returns .NET framework objects, whereas Python is an interpreted programming language

The Python interpreter takes the human-readable code and creates another form of code which is understood by the interpreter, to be changed later to a machine-readable code where the actual execution happens.

Let's now start with the basics of both languages, such as commenting, declaring variables, conditions, and other basics, to get a better sense of their similarities and differences.

Commenting

Making a single line comment in PowerShell or Python is identical - use the hash sign (#) at the beginning of the line like below.

# This is a powerShell comment and will not be executed

# This is a Python comment and will not be executed.

Declaring Variables

All variables in PowerShell start with a $ followed by a name. Below you can see how a variable is assigned to hold an integer.

$var = 1

Defining string variables works the same way in PowerShell, but you'll need to enclose the value in single or double quotes.

$var2 = "string"
$var3 = 'string'

Check out the about_Variables document for more information about PowerShell variables.

In Python, variables are treated nearly identical but do not require the variable to start with an $.

var1 = 7
var2 = "string"
var3 = 'string'

You can learn more about Python variables via W3Schools other many other online resources.

Working with Math Operations

In PowerShell and Python, any positive or negative number without decimals is an integer. By default, they will be automatically assigned to a variable of type integer. Math operations can be executed normally on these variables.

In PowerShell, you can see some examples of some basic math operations below.

$int1 = 70
$int2 = 77
$int3 = -10
$int1 + $int2
$int2 - $int1
$int1 + $Int3

Check out the How to do Math in PowerShell series on RedmondMag for more information.

Similarly, in Python, you can do basic math operations as well shown below.

int1 = 70
int2 = 77
int3 = -10
int1 + int2
int2 - int1
int1 + int3

Learn more about math operations in Python in this helpful geeks2geeks.com article.

Making use of Conditional Statements

Conditional statements are important to any programming language. Conditional statements allow the developer to redirect the flow of the code, depending on one or more conditions. When you get into conditional statements like if/then constructs, you'll find that PowerShell and Python are nearly identical.

You can see below that there is a slight, but very important, difference between the two languages. PowerShell is heavily dependent on parentheses ( ), curly braces { }, and other special characters, but Python uses indentation.

Notice all of the parentheses and curly braces below in the PowerShell example.

if (Condition) {
    Code to be executed if the condition is true
} else {
    Other code to be executed if the condition is false
}

Contradict PowerShell code with the Python code below. You will only see colons to indicate the end of conditional statements and spaces to indicate the code to execute inside.

if condition:
    Code to be executed if the condition is true
else:
    Other code to be executed if the condition is false

To demonstrate, let's see how a typical PowerShell if/then statement looks and behaves. When the below code is run, you will see an output of 77 is greater than 70.

$var1 = 77
$var2 = 70
if ($var1 -gt $var2) {
    Write-Host -Object "$var1 is greater than $var2"
} else {
    Write-host -Object "$var1 is less than $var2"
}

In contrast, notice how the same task is performed in Python. There are quite a few differences including different operators and commands to output text to the console.

if var1 > var2:
    print(f"{var1} is greater than {var2}")
else:
    print(f"{var1} is less than {var2}")

Looping

Another important concept in programming languages is looping. Loops allow a language to repeat, or iterate over, a piece of code continually until a condition is met, or for a certain number of times.

In PowerShell, a common foreach statement would look like below.

foreach ($item in $list) {
	Code to be executed for each item
}

In Python, a similar loop performing the same task would use a for loop as shown below.

for item in list:
	Code to be executed for each item

There is a great deal of similarity in the syntax used by PowerShell and Python, especially for the basics and core use of the languages. These similarities are a huge advantage for the anyone who masters PowerShell and wants to learn more about Python, or vice versa.

Solving the Same Problem Differently

Let's now show how to solve a common problem a little differently with both PowerShell and Python. To do that, we're going to read a simple text file with line-delimited numbers and only return a certain range of numbers to the console.

The file we'll be using is called input_text.txt and line-delimited numbers contains a wide range of numbers from 1 to 6345.

We'll create a function in both PowerShell and Python to process all of the numbers returned from the file.

Processing a File with PowerShell

Below you will see how you could make this happen in PowerShell.

## Define a function called Get-TwoDigits
function Get-TwoDigits {
    [CmdletBinding()]
    param(
        [Parameter()]
        $List ## Provide an input parameter called List representing numbers
    )
    ## Loop over each number in List. If the number is greater than 9 and less
    ## then 99, return that number to the conosle
    foreach($num in $List){
        if($num -gt 9 -and $num -le 99 ){
            Write-Host $num
        }
        
    }
}

## Read the text file and place contents into an array called inputlist
PS51> $inputlist = Get-Content -Path .\\input_text.txt

## Call the function providing the contents of the file as the List parameter
PS51> Get-TwoDigits -List $inputlist

When you run Get-TwoDigits, you will see that PowerShell will only return any number in input_text.txt that is between 9 and 99.

Processing a File with Python

Now, we'll perform the exact same steps with Python to notice the syntax differences.

## Open the file handle using the open() method
File_Read = open("/PS_Vs._PY/input_text.txt")

## Read the file and split the large string up into an array with the splitlines() method
inputData = (File_Read.read().splitlines())

## Close the open file handle
File_Read.close()

## Define a function called two_digits with a single parameter called input_list
def two_digits (input_list):
    ## Loop over each number in List. If the number is greater than 9 and less
    ## then 99, return that number to the conosle
    for num in input_list:
        if (int(num) > 9) and (int(num) <= 99):
            print(num)


>>> two_digits(inputData)

When you run the two_digits() function, you will see that Python will only return any number in input_text.txt that is between 9 and 99.

Creating a function in Python is almost the same structure. Keep in mind that indentation is vital in Python, as is case sensitivity.

Further Reading