This article is contributed. See the original author and article here.

During MS Ignite 2020, I was surprised to learn of a growing debate that system administrators are starting to become increasing vocal on…

“Which scripting language is better? Python or PowerShell?”

 

Having only dabbled in both, I am not an authority on either to share my opinion.  From a fact’s perspective, PowerShell provides a shell scripting environment whereas Python is an interpreted high-level programming language. Both can accomplish similar tasks but thier differences also help distinguish themselves to complete certain tasks.

 

So why not use both?  

 

This was a question I began to research for this post and thought it would be an innovative idea to compare the similarities in syntax between Python and PowerShell.  In conducting said research I came across the work by Adam Driscoll, an 8 year MVP in the Cloud and Datacenter space and added a few subtle changes. 

  

Here is the reference between PowerShell and Python language syntax. Let us know in the comments below if something is missing or should be added.
 

Syntax Reference
 

Arrays

  PowerShell Python
Defining
@('Hello', 'World')
['Hello', 'World']
Access Element
$arr = @('Hello', 'World')
$arr[0]
# Hello
arr = ['Hello', 'World']
arr[0]
# 'Hello'
Length
$arr = @('Hello', 'World')
$arr.Length
arr = ['Hello', 'World']
len(arr)
Adding
$arr = @('Hello', 'World')
$arr += "Friend"
arr = ['Hello', 'World']
arr.append('Friend')
Removing
 $arr = [System.Collections.ArrayList]@('Hello', 'World')
 $arr.RemoveAt($arr.Count - 1)
arr = ['Hello', 'World']
arr.pop(1)
Removing by value
 $arr = [System.Collections.ArrayList]@('Hello', 'World')
 $arr.Remove("Hello")
arr = ['Hello', 'World']
arr.remove('Hello')

 
Casting

  PowerShell Python
Integers
$i = [int]"10"
i = int("10")
Floats
$i = [float]"10.5" 
i = float("10.5")
Strings
$i = [string]10
i = str(10)

Classes

  PowerShell Python
Definition
class MyClass {
    $x = 5
}
class MyClass:
  x = 5
Create Object
[MyClass]::new()
MyClass()
Constructor
class Person {
    Person($Name, $Age) {
        $this.Name = $Name
        $this.Age = $Age
    }

    $Name = ''
    $Age = 0
}
[Person]::new('Orin', 40)
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("Orin", 40)
Methods
class Person {
    Person($Name, $Age) {
        $this.Name = $Name
        $this.Age = $Age
    }

    [string]myfunc() {
        return "Hello my name is $($this.Name)"
    }

    $Name = ''
    $Age = 0
}
[Person]::new('Thomas', 32)
class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("Thomas", 32)
p1.myfunc()

Conditions

  PowerShell Python
If Else
$a = 33
$b = 200
if ($b -gt $a)
{
    Write-Host "b is greater than a"
}
elseif ($a -eq $b)
{
    Write-Host "a and b are equal"  
}
else
{
  Write-Host "a is greater than b"
}
  
a = 33
b = 200
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

Comments

  PowerShell Python
Single line
# Hello, world!
# Hello, world!
Multiline
<# 
Hello, world!
#>
"""
Hello, world!
"""

Data Types

  PowerShell Python
Get Type
$var = 1
$var | Get-Member
#or
$var.GetType()
var = 1
type(var)

Dictionaries

  PowerShell Python
Defining
$thisdict = @{
  brand = "Dodge"
  model = "Challenger"
  year = 1970
}
thisdict = {
  "brand": "Dodge",
  "model": "Challenger",
  "year": 1970
}
print(thisdict)
Accessing Elements
$thisdict = @{
  brand = "Dodge"
  model = "Challenger"
  year = 1970
}
$thisdict.brand
$thisdict['brand']
thisdict = {
  "brand": "Dodge",
  "model": "Challenger",
  "year": 1970
}
thisdict['brand']
Updating Elements
$thisdict = @{
  brand = "Dodge"
  model = "Challenger"
  year = 1970
}
$thisdict.brand = 'Fiat'
thisdict = {
  "brand": "Dodge",
  "model": "Challenger",
  "year": 1970
}
thisdict['brand'] = 'Fiat'
Enumerating Keys
$thisdict = @{
  brand = "Dodge"
  model = "Challenger"
  year = 1970
}
$thisdict.Keys | ForEach-Object {
    $_
}
thisdict = {
  "brand": "Dodge",
  "model": "Challenger",
  "year": 1970
}
for x in thisdict:
    print(x)
Enumerating Values
$thisdict = @{
  brand = "Dodge"
  model = "Challenger"
  year = 1970
}
$thisdict.Values | ForEach-Object {
    $_
}
thisdict = {
  "brand": "Dodge",
  "model": "Challenger",
  "year": 1970
}
for x in thisdict.values():
    print(x)
Check if key exists
$thisdict = @{
  brand = "Dodge"
  model = "Challenger"
  year = 1970
}
if ($thisdict.ContainsKey("model"))
{
    Write-Host "Yes, 'model' is one of the keys in the thisdict dictionary"
}
thisdict = {
  "brand": "Dodge",
  "model": "Challenger",
  "year": 1970
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")
Adding items
$thisdict = @{
  brand = "Dodge"
  model = "Challenger"
  year = 1970
}
$thisdict.color = 'Plum Crazy Purple'
thisdict = {
  "brand": "Dodge",
  "model": "Challenger",
  "year": 1970
}
thisdict["color"] = "Plum Crazy Purple"

Functions

  PowerShell Python
Definition
function my-function()
{
  Write-Host "Hello from a function"  
}
my-function
def my_function():
  print("Hello from a function")

my_function()
Arguments
function my-function($fname, $lname)
{
    Write-Host "$fname $lname"
}
  

my-function -fname "Anthony" -lname "Bartolo"
def my_function(fname, lname):
  print(fname + " " + lname)

my_function("Anthony", "Bartolo")
Variable Arguments
function my-function()
{
    Write-Host "$($args[2])"
}
  
my-function "Sarah" "Pierre" "Rick"
def my_function(*team):
  print("The team member is " + team[1])

my_function("Sarah", "Pierre", "Rick")
Named Arguments
function my-function($team3, $team2, $team1)
{
    Write-Host "The youngest team member is $team3"
}
  
my-function -team1 "Rick" -team2 "Pierre" -team3 "Sarah"
def my_function(team3, team2, team1):
  print("The youngest team is " + team3)

my_function(team1 = "Rick", team2 = "Pierre", team3 = "Sarah")
Default Values
function my-function
{
    param(
        $country = "Canada"
    )

    Write-Host "I am from $country"
}
def my_function(country = "Canada"):
  print("I am from " + country)
Return Values
function my-function($x)
{
    5 * $x
}
  
def my_function(x):
  return 5 * x

Lambdas

  PowerShell Python
Lambda
$x = { param($a) $a + 10 }
& $x 5
x = lambda a : a + 10
print(x(5))

Loops

  PowerShell Python
For
$fruits = @("strawberry", "banana", "mango")
foreach($x in $fruits)
{
    Write-Host $x
}
  
fruits = ["strawberry", "banana", "mango"]
for x in fruits:
  print(x)
While
$i = 1
while ($i -lt 6)
{
    Write-Host $i
    $i++
}
i = 1
while i < 6:
  print(i)
  i += 1
Break
$i = 1
while ($i -lt 6)
{
    Write-Host $i
    if ($i -eq 3)
    {
        break
    }
    $i++
}
i = 1
while i < 6:
   print(i)
   if i == 3:
     break
  i += 1
Continue
$i = 1
while ($i -lt 6)
{
    Write-Host $i
    if ($i -eq 3)
    {
        continue
    }
    $i++
}
i = 1
while i < 6:
   print(i)
   if i == 3:
     continue
  i += 1

Operators

  PowerShell Python
Addition
$var = 1 + 1
var = 1 + 1
Subtraction
$var = 1 - 1
var = 1 - 1
Multiplication
$var = 1 * 1
var = 1 * 1
Division
$var = 1 / 1
var = 1 / 1
Modulus
$var = 1 % 1
var = 1 % 1
Floor
[Math]::Floor(10 / 3)
10 // 3
Exponent
[Math]::Pow(10, 3)
10 ** 3

Packages

  PowerShell Python
Install
Install-Module PowerShellProtect
pip install camelcase
Import
Import-Module PowerShellProtect
import camelcase
List
Get-Module -ListAvailable
pip list

Strings

  PowerShell Python
String
"Hello"
"Hello"
'Hello'
Multiline
"Hello
World
"
"""Hello
World"""
Select Character
$str = 'Hello'
$str[0]
# H
str = 'Hello'
str[0]
# 'H'
Length
$str = 'Hello'
$str.Length
str = 'Hello'
len(str)
Remove whitespace at front and back
$str = ' Hello '
$str.Trim()
# Hello
str = ' Hello '
str.strip()
# 'Hello'
To Lowercase
$str = 'HELLO'
$str.ToLower()
# hello
str = 'HELLO'
str.lower()
# 'hello'
To Uppercase
$str = 'hello'
$str.ToUpper()
# HELLO
str = 'hello'
str.upper()
# 'HELLO'
Replace
$str = 'Hello'
$str.Replace('H', 'Y')
# Yello
str = 'Hello'
str.replace('H', 'Y')
# 'Yello'
Split
'Hello, World' -split ','
# @('Hello', ' World')
str = 'Hello, World'
str.split(',')
# ['Hello', ' World']
Join
$array = @("Hello", "World")
$array -join ", "
[String]::Join(', ', $array)
list = ["Hello", "World"]
", ".join(list)
Formatting
$price = 40
$txt = "The price is {0} dollars"
$txt -f $price
price = 40
txt = "The price is {} dollars"
print(txt.format(price))
Formatting by Index
$price = 40
$txt = "The price is {0} dollars"
$txt -f $price
price = 40
txt = "The price is {0} dollars"
print(txt.format(price))
Formatting Strings
$price = 40
"The price is $price dollars"
price = 40
f"The price is {price} dollars"

Try Catch

  PowerShell Python
 
try {
    Write-Host $x 
} catch {
    Write-Host "An exception ocur Plum Crazy Purple"
}
try:
  print(x)
except:
  print("An exception occur Plum Crazy Purple")

Variables

  PowerShell Python
 
$var = "Hello"
var = "Hello"
Global
$global:var = "Hello"
global var
var = "Hello"

Brought to you by Dr. Ware, Microsoft Office 365 Silver Partner, Charleston SC.