PowerShell and Python are powerful programming languages with many similarities. While PowerShell is technically a shell scripting language (like Bash), functionally it has a lot more in common with Python, and can be used to generate scripts of equal complexity.

As someone with a strong familiarity with PowerShell, I’m finding it useful as I learn Python to reference the equivalent concepts in PowerShell.

Adam Driscoll did this previously in 2020 and his page is incredibly helpful. Below I’ve followed a similar approach, and have used the topics covered by the W3Schools Python tutorial as a guide. For each concept I’ve provided a side by side comparison with the closest equivalent from PowerShell.

The examples given below have been tested as working in PowerShell 7.4.7 and Python 3.13.3.

Get started

ConceptPowerShellPython
Check installed version
($PSVersionTable).PSVersion
7.4.7
python --version
Python 3.13.3
Hello World
Write-Host "Hello, World!"
Hello, World!

Alternatively use Write-Output to return a PowerShell object.

print("Hello, World!")
Hello, World!
Comments
#This is a comment
Write-Host "Hello, World!" #This too

<# This is a
multiline comment #>
#This is a comment
print("Hello, World!") #This too

# This is a
# multiline comment

Unofficially, you can also use ''' for multiline comments, which are ignored unless used as docstrings.

Variables

  • In both languages, a variable is created the moment you first assign a value to it.
  • Variables are scoped based on where they are declared: PowerShell | Python.
  • Variables do not need to be declared with a specific type, and can change type after being set. You can however use casting to specify the data type.
ConceptPowerShellPython
Creating variables
$myVariable = 5
$text = 'sometext'

PowerShell variable names are case-insensitive, $text is the same as $Text.

myVariable = 5
text = 'sometext'

Python variable names are case-sensitive text is not the same as Text.

Casting
$x = [string]3   # '3'
$y = [int]3
$z = [double]3.14

float in PowerShell maps to System.Single which is a 32 bit floating-point number. double is used in the example above to be equivalent to the Python float which uses a 64 bit integer.

x = str(3)   # '3'
y = int(3)
z = float(3.14)

float in Python is a 64 bit floating-point number.

Assign multiple values
$x,$y,$z = 1,2,3
x,y,z = 1,2,3

Data Types

  • Lists and tuples are standard Python data types that store values in a sequence. Sets are another standard Python data type that also store values. The major difference is that sets, unlike lists or tuples, cannot have multiple occurrences of the same element and store unordered values.
ConceptPowerShellPython
Built-in Data Types
$x = "some string"             #string
$x = 20                        #int
$x = 20.5                      #double
$x = "ben","max","kim"         #array

$x = 0..5                      #range
$x = @{name = "ben"; age = 36} #hashtable

$x = $true                     #bool
x = "some string"                #str
x = 20                           #int
x = 20.5                         #float
x = ["ben","max","kim"]          #list
x = ("ben","max","kim")          #tuple
x = range(6)                     #range
x = {"name" : "ben", "age" : 36} #dict
x = {"ben", "max", "kim"}        #set
x = True                         #bool
Assign multiple values
$x,$y,$z = 1,2,3
x,y,z = 1,2,3

Strings

  • In both languages, strings can be specified via single or double quotes.
  • Both languages have a number of built-in methods you can use on strings, but they differ. For a full list of methods see these pages: PowerShell | Python
ConceptPowerShellPython
Quotation marks
$str1 = 'this is a string'
$str2 = "this is also a string"

In PowerShell you can interpolate variables inside a double quoted string:

$name = 'Mark'
Write-Host "my name is $name"
Write-Host 'my name is ' + $name
my name is Mark
my name is Mark
str1 = 'this is a string'
str2 = "this is also a string"

In Python you can interpolate variables in any string. The below uses the f-string method:

name = 'Mark'
print(f"my name is {name}")
print(f'my name is {name}')
my name is Mark
my name is Mark
Multiline strings
$str1 = @"
This is
a multiline
string
"@

$str2 = @'
This is also
a multiline
string
'@
str1 = """
This is
a multiline
string
"""

str2 = '''
This is also
a multiline
string
'''
String length
"This is a string".length
16
print(len("This is a string"))
16
String methods
$str = 'heLLo'

$str.padleft(8)           # --> '   heLLo'
$str.padright(8)          # --> 'heLLo   '
$str.tolower()            # --> 'hello'
$str.toupper()            # --> 'HELLO'
$str.replace('LL','YY')   # --> 'heYYo'
str = 'heLLo'

str.rjust(8)             # --> '   heLLo'
str.ljust(8)             # --> 'heLLo   '
str.lower()              # --> 'hello'
str.upper()              # --> 'hello'
str.replace('LL','YY')   # --> 'heYYo'

Arrays

  • Python does not have built-in support for arrays, but Python Lists can be used instead, as demonstrated in the below examples. You can get arrays via the NumPy module.
  • PowerShell has arrays, but once defined they are a fixed length. To append a new item PowerShell recreates the entire array with the new element. You can alternatively use [System.Collections.ArrayList] which is a dynamic array that behaves more like Python Lists.
ConceptPowerShellPython
Create an array
$basket = @("apple","pear","plum")
$basket

apple
pear
plum
basket = ["apple","pear","plum"]
for fruit in basket:
  print(fruit)
apple
pear
plum
Array length (number of elements)
$basket = @("apple","pear","plum")
$basket.count
3
basket = ["apple","pear","plum"]
print(len(basket))
3
Add an item to an array
$basket = @("apple","pear","plum")
$basket += "banana"
basket = ["apple","pear","plum"]
basket.append("banana")
Remove an item from an array
$basket = @("apple","pear","plum")
$basket = $basket | where { $_ -ne "banana" }

Alternatively you could define a [System.Collections.ArrayList] object which has add and remove methods.

basket = ["apple","pear","plum"]
basket.remove("banana")

This will only remove the first occurrence of the specified value.

Sort an array
$basket = @("apple","pear","plum","banana")
$basket | Sort-Object
$basket

apple
banana
pear
plum

Alternatively you could define a [System.Collections.ArrayList] object which has a sort method.

basket = ["apple","pear","plum","banana"]
basket.sort()
for fruit in basket:
  print(fruit)
apple
banana
pear
plum

Sorts the list ascending by default. Use sort(reverse=True) to specify descending.

Dictionaries

  • Dictionaries are a collection of key value pairs. In PowerShell a dictionary is referred to as a hashtable.
  • In both languages, dictionaries (hashtables) are changeable: you can modify/add/remove items after creation. Dictionary keys must be unique.
ConceptPowerShellPython
Creation
$car = @{
  brand = "Audi"
  model = "Q7"
  year = 2019
}

You can specify an ordered hashtable by adding the [ordered] type accelerator.

car = {
  "brand": "Audi",
  "model": "Q7",
  "year": 2019
}

As of Python 3.7, dictionaries are ordered by default. Prior to 3.7 they are unordered.

Return an item
$car["brand"]
Audi
print(car["brand"])
Audi
List keys
$car.keys
year
brand
model
print(car.keys())
dict_keys(['brand', 'model', 'year'])

The list of the values is a view of the dictionary. Any changes to the dictionary will be reflected in the list.

List items
$car.values
2019
Audi
Q7
print(car.items())
dict_items([('brand', 'Audi'),
  ('model', 'Q7'),
  ('year', 2019)])

The list of the values is a view of the dictionary. Any changes to the dictionary will be reflected in the list.

Check if a key exists
if ('model' -in $car.Keys) {
  $true
}
if "model" in car:
  print(True)

Add or update an item
$car["color"] = "Blue"
car["color"] = "Blue"
Remove an item
$car.remove("color")
car.pop("color")
Remove all items
$car.clear()
car.clear()
Dictionary length
$car.count
3
print(len(car))
3

Dates

  • To work with dates in Python you need to import the built-in datetime module.
ConceptPowerShellPython
Return the current date/time
$now = Get-Date


$now
$now.day
$now.month
$now.year
17 May 2025 13:27:16
17
5
2025
import datetime
now = datetime.datetime.now()

print(now)
print(now.day)
print(now.month)
print(now.year)
2025-05-17 12:28:25.903551
17
5
2025
Create a date object
$x = Get-Date -Day 17 -Month 5 -Year 2025

Time parameters can also be specified, their default is the current time.

import datetime
x = datetime.datetime(2025, 5, 17)

Time parameters can also be specified, their default is 0.

Formatting dates
$x = Get-Date -Day 17 -Month 5 -Year 2025


Get-Date $x -UFormat '%a' # --> Sat
Get-Date $x -UFormat '%A' # --> Saturday
Get-Date $x -UFormat '%w' # --> 6
Get-Date $x -UFormat '%d' # --> 17
Get-Date $x -UFormat '%b' # --> May
Get-Date $x -UFormat '%m' # --> 05
Get-Date $x -UFormat '%y' # --> 25
Get-Date $x -UFormat '%Y' # --> 2025

See here for the full list of supported Python datetime formatting codes.

import datetime
x = datetime.datetime(2025, 5, 17)

x.strftime("%a") # --> Sat
x.strftime("%A") # --> Saturday
x.strftime("%w") # --> 6
x.strftime("%d") # --> 17
x.strftime("%b") # --> May
x.strftime("%m") # --> 05
x.strftime("%y") # --> 25
x.strftime("%Y") # --> 2025

See here for the full list of supported PowerShell datetime formatting codes.

Files

  • PowerShell has built-in cmdlets for working with files.
  • Python has built-in functions for creating, reading and writing to files. File deletion requires the os module.
ConceptPowerShellPython
Read from a file
$f = Get-Content "file.txt"
$f
f = open("file.txt")
print(f.read())
Write to a file
# Use Add-Content to append a file
'Some content' | Add-Content "file.txt"


# Use Set-Content to overwrite a file
'New content' | Set-Content "file.txt"

# Use "a" to append a file
with open("file.txt", "a") as f:
  f.write("Some content")

# Use "w" to overwrite a file
with open("file.txt", "w") as f:
  f.write("New content")
New file
# Use New-Item to create a file
New-Item "file.txt" -ItemType "File"
# Use "x" to create a file
open("file.txt", "x")
Delete files
# Use Remove-Item to delete a file
Remove-Item "file.txt"

# File delete requires os module remove()
import os
os.remove("file.txt")
Check if a file exists
# Use Test-Path to check exists
if (Test-Path "file.txt") {
  #..
}
# File exists requires os module exists()
import os
if os.path.exists("file.txt"):
  #..

JSON

  • To work with JSON in Python you need to import the built-in json module.
ConceptPowerShellPython
Convert from JSON
# ConvertFrom-Json is built-in
$x = '{"name":"Bob","age":30,"city":"Bath"}'
$y = $x | ConvertFrom-Json
$y.name
$y.age
$y.city

PowerShell converts JSON to a PSCustomObject.

Bob
30
Bath
import json
x = '{ "name":"Bob","age":30,"city":"Bath"}'
y = json.loads(x)
print(y["name"])
print(y["age"])
print(y["city"])

Python converts JSON to a dictionary object.

Bob
30
Bath
Convert to JSON
# ConvertTo-Json is built-in
$x = @{
  name = "Bob"
  age  = 30
  city = "Bath"
}

$y = $x | ConvertTo-Json
$y

The ConvertTo-Json cmdlet converts any .NET object to JSON. The properties become the name / values, and the methods are removed.

{
  "age": 30,
  "name": "Bob",
  "city": "Bath"
}
import json
x = {
  "name": "Bob",
  "age": 30,
  "city": "Bath"
}

y = json.dumps(x)
print(y)

Python objects are converted into the JSON equivalent: dict –> object, list, tuple –> array, str –> string, int, float –> number, True/False –> true/false, None –> null.

{"name":"John","age": 30,"city":"New York"}

You can further customise the indentation, separators and sorting as follows (these can also be combined):

json.dumps(x, indent=4)
json.dumps(x, separators=(". ", " = "))
json.dumps(x, sort_keys=True)

Operators

ConceptPowerShellPython
Arithmetic
$a + $b                  # Addition
$a - $b                  # Subtraction
$a * $b                  # Multiplication
$a / $b                  # Division
$a % $b                  # Modulus
[Math]::Pow($a, $b)      # Exponentiation
[math]::floor($a / $b)   # Floor division
a + b    # Addition
a - b    # Subtraction
a * b    # Multiplication
a / b    # Division
a % b    # Modulus
a ** b   # Exponentiation
a // b   # Floor division
Assignment
$x += 3   # --> x = x + 3 (add)
$x -= 3   # --> x = x - 3 (subtract)
$x *= 3   # --> x = x * 3 (multiply)
$x /= 3   # --> x = x / 3 (divide)
$x %= 3   # --> x = x % 3 (modulus)
x += 3    # --> x = x + 3 (add)
x -= 3    # --> x = x - 3 (subtract)
x *= 3    # --> x = x * 3 (multiply)
x /= 3    # --> x = x / 3 (divide)
x %= 3    # --> x = x % 3 (modulus)
x **= 3   # --> x = x ** 3 (exponentiation)
x //= 3   # --> x = x // 3 (floor divide)
Comparison
$a -eq $b   # Equals
$a -ne $b   # Not equals
$a -lt $b   # Less than
$a -le $b   # Less than or equal to
$a -gt $b   # Greater than
$a -ge $b   # Greater than or equal to
a == b   # Equals
a != b   # Not equals
a < b    # Less than
a <= b   # Less than or equal to
a > b    # Greater than
a >= b   # Greater than or equal to
Escape characters
"This is `"how`" to escape" # Escape next
"This is `n on two lines"   # new line
"`tThis has a tab space"    # tab space
"This is \"how\" to escape" # Escape next
"This is \n on two lines"   # new line
"\tThis has a tab space"    # tab space
Logical
($a -gt 5) -and ($b -lt 10)
($a -gt 5) -or ($b -lt 10)
-not ($a -gt 5 -and $b -lt 10)
(a > 5) and (b < 10)
(a > 5) or (b < 10)
not(a > 5 and b < 10)
Membership
$a = 1,2,3
3 -in $a       # True
4 -in $a       # False
3 -notin $a    # False

PowerShell also has the -contains operator.

a = (1,2,3)
3 in a     # True
4 in a     # False
3 not in a # False

Conditionals

  • Python uses indentation to define the code that belongs to a conditional statement. PowerShell uses curly braces.
ConceptPowerShellPython
if / else-if / else
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"
}
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")

switch / match
switch ($day) {
    1..5 {
        Write-Host "weekday"
    }
    6..7 {
        Write-Host "weekend"
    }
    default {
        throw "day out of range"
    }
}
match day:
  case 1 | 2 | 3 | 4 | 5:
    print("weekday")

  case 6 | 7:
    print("weekend")

  case _:
    raise Exception("day out of range")


Iteration

  • Python doesn’t have a do..until loop, but you can achieve the same result by negating the condition of a while loop.
ConceptPowerShellPython
While Loops
$i = 1

while ($i -le 5) {
  $i
  $i += 1
}
i = 1

while i <= 5:
  print(i)
  i += 1

For Loops
for ($i = 0; $i -lt 21; $i++){
    Write-Host $i
}

Iterate a set number of times at a custom increment (2 in this example):

for ($i = 0; $i -lt 21; $i += 2){
    Write-Host $i
}
for i in range(0, 21):
    print(i)

Iterate a set number of times at a custom increment (2 in this example):

for i in range(0, 21, 2):
    print(i)

ForEach Loops

Iterate over a collection with a foreach loop:

$fruits = "apple", "banana", "cherry"

foreach ($fruit in $fruits) {
  Write-Host $fruit
}

PowerShell also has foreach-object for iterating objects via the pipeline.

$fruits | foreach-object {
  Write-Host $_
}

Iterate over a list with a for loop:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
  print(fruit)

Functions

  • Python uses indentation to define the code that belongs to a function. PowerShell uses curly braces.
  • In PowerShell a param() block can also be used to define function input parameters (arguments), with additional validation.
ConceptPowerShellPython
Defining and calling a function
function sayHello {
  Write-Host "Hello"
}

sayHello
Hello
def sayHello():
  print("Hello")


sayHello()
Hello
Function arguments / parameters
function sayHello($name) {
  Write-Host "Hello $name"
}

sayHello "Sarah"
Hello Sarah
function sayHello($fname, $lname) {
  Write-Host "Hello $fname $lname"
}

sayHello "Bob" "Bilby"
Hello Bob Bilby

Parameters can be invoked by name:

sayHello -fname "Bob" -lname "Bilby"
def sayHello(name):
  print(f"Hello {name}")


sayHello("Sarah")
Hello Sarah
def sayHello(fname,lname):
  print(f"Hello {fname} {lname}")


sayHello("Bob", "Bilby")
Hello Bob Bilby

Parameters can be invoked by name:

sayHello(fname = "Bob", lname = "Bilby")
Argument / parameter default values
function sayHello($name, $co = "BobCo") {
  Write-Host "Hello $name from $co"
}

sayHello "Jeff"
Hello Jeff from BobCo
def sayHello(name,co = "BobCo"):
  print(f"Hello {name} from {co}")


sayHello("Jeff")
Hello Jeff from BobCo
Arbitrary arguments *args
function sayHello() {
  foreach ($name in $args) {
    Write-Host "Hello $name"
  }
}

sayHello "Jeff" "Bob" "Sarah"
Hello Jeff
Hello Bob
Hello Sarah
def sayHello(*names):
  for name in names:
    print(f"Hello {name}")



sayHello("Jeff", "Bob", "Sarah")
Hello Jeff
Hello Bob
Hello Sarah
Arbitrary keyword arguments **kwargs
function personDetails($person) {
  foreach ($p in $person.getenumerator()) {
    Write-Host "$($p.key)`: $($p.value)"
  }
}

personDetails @{fn = "Bob"; ln = "Bilby"}
def personDetails(**person):
  for key in person:
    print(f"{key}: {person[key]}")


personDetails(fn = "Bob", ln = "Bilby")
Return values
function multiplyBy5 ($x) {
  return ($x * 5)
}

multiplyBy5 5
25
def multiplyBy5 (x):
    return (x * 5)


print(multiplyBy5(5))
25
Empty function
function emptyFunction {}

def emptyFunction:
  pass

Classes

  • Both languages are object oriented. Almost everything is an object with properties and methods.
  • A Class is a way to define a custom object’s structure.
ConceptPowerShellPython
Class with a fixed property
Class Customer {
  $Bank = "GlobalBank"
}

# Example usage:
$c = [Customer]::new()
$c.Bank
GlobalBank
class Customer:
  Bank = "GlobalBank"

# Example usage:
c = Customer()
print(c.Bank)
GlobalBank
Class with assignable properties
Class Customer {
  [string]$name
  [decimal]$balance

  $Bank = "GlobalBank"

  Customer($name, $balance = 0) {
    $this.name = $name
    $this.balance = $balance
  }
}

# Example usage:
$c = [Customer]::new("Alice",100)
$c.name
$c.balance
Alice
100
class Customer:
  bank = "GlobalBank"

  def __init__(self, name, balance=0):
    self.name = name
    self.balance = balance

# Example usage:
c = Customer("Alice",100)
print(c.name)
print(c.balance)
Alice
100
Class with properties and methods
Class Customer {
  [string]$name
  [decimal]$balance

  $Bank = "GlobalBank"

  Customer($name, $balance = 0) {
    $this.name = $name
    $this.balance = $balance
  }

  [void]Deposit($amount) {
    if ($amount -le 0) {
      throw "Negative deposit."
    }
    $this.balance += $amount
  }

  [void]Withdraw($amount) {
    if ($amount -gt $this.balance) {
      throw "Insufficient funds."
    }
    $this.balance -= $amount
  }

  [string]ToString() {
    $fbalance = "£{0:N2}" -f $this.balance
    return "$($this.name): $fbalance"
  }
}

# Example usage:
$c = [Customer]::new("Alice", 100)
$c.Deposit(50)
$c.Withdraw(30)
$c.ToString()
Alice: £120.00
class Customer:

  bank = "GlobalBank"

  def __init__(self, name, balance=0):
    self.name = name
    self.balance = balance

  def deposit(self, amount):
    if amount <= 0:
        raise ValueError("Negative deposit.")

    self.balance += amount

  def withdraw(self, amount):
    if amount > self.balance:
        raise ValueError("Insufficient funds.")

    self.balance -= amount

  def __str__(self):
    fbalance = f{self.balance:.2f}"
    return f"{self.name}: {fbalance}"


# Example usage:
c = Customer("Alice", 100)
c.deposit(50)
c.withdraw(30)
print(c)
Alice: £120.00

Modules

  • In both languages, a module is simply a collection of functions that you want to include in another script or application.
  • In Python modules are discovered via the module search path:

    When a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path.

ConceptPowerShellPython
Use a module
# Save this in a file called MyModule.ps1
function greeting($name):
  Write-Host "Hello, $name"

# In your main file
Import-Module MyModule.ps1

greeting "Mark"
# Save this in a file called MyModule.py
def greeting(name):
  print("Hello, {name}")

# In your main file
import MyModule

MyModule.greeting("Mark")
List the functions in a module
Import-Module MyModule.ps1

(Get-Command -Module MyModule).Name

import MyModule

for name in dir(MyModule):
  print(name)
Import a specific function
Import-Module MyModule -Function "greeting"
from MyModule import greeting
Install a module
Install-Module SomeModule
pip install SomeModule
Uninstall a module
Uninstall-Module SomeModule
pip uninstall SomeModule
List installed modules
# List modules installed via PowerShellGet
Get-InstalledModule
# List modules installed via pip
pip list

Exceptions

  • PowerShell and Python have similar concepts for handling excpetions, with try..catch and try..except being functionally similar. Both support catching multiple specific exception types and a finally block for performing post-exception clean up tasks, such as closing connections or removing temporary files.
ConceptPowerShellPython
Raise an exception
throw 'An exception occurred'
raise Exception("An exception occurred")
Catch exceptions
try {
  Write-Host $x -ErrorAction Stop
}
catch {
  Write-Error ("An exception occurred")
}
try:
  print(x)

except:
  print("An exception occurred")

Catch multiple exceptions
try {
  Get-Content .\file.txt -ErrorAction Stop
}
catch [System.IO.IOException] {
  Write-Error "A file error occurred"
}
catch {
  Write-Error "A different error occurred"
}
try:
  f = open('file.txt', 'w')

except OSError:
  print("A file error occurred")

except:
  print("A different error occurred")

Execute code after an exception
try {
  $f = [System.IO.File]::Open("file.txt")
}
catch {
  Write-Error "Failed to open"
}
finally {
  $f.close()
}
try:
  f = open('file.txt', 'w')

except:
  print("Failed to open")

finally:
  f.close()

Updated:

Comments