basket = ["apple","pear","plum"]
print(len(basket))
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
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)
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.
|
Concept | PowerShell | Python |
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 |
|
|
List 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 |
|
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 |
|
|
Remove an item |
|
|
Remove all items |
|
|
Dictionary length |
|
|
Dates
- To work with dates in Python you need to import the built-in
datetime module.
|
Concept | PowerShell | Python |
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.
|
Concept | PowerShell | Python |
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.
|
Concept | PowerShell | Python |
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.
|
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.
|
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)
|
|
Concept | PowerShell | Python |
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.
|
Concept | PowerShell | Python |
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.
|
Concept | PowerShell | Python |
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.
|
Concept | PowerShell | Python |
Defining and calling a function |
function sayHello {
Write-Host "Hello"
}
sayHello
|
def sayHello():
print("Hello")
sayHello()
|
Function arguments / parameters |
function sayHello($name) {
Write-Host "Hello $name"
}
sayHello "Sarah"
function sayHello($fname, $lname) {
Write-Host "Hello $fname $lname"
}
sayHello "Bob" "Bilby"
Parameters can be invoked by name:
sayHello -fname "Bob" -lname "Bilby"
|
def sayHello(name):
print(f"Hello {name}")
sayHello("Sarah")
def sayHello(fname,lname):
print(f"Hello {fname} {lname}")
sayHello("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"
|
def sayHello(name,co = "BobCo"):
print(f"Hello {name} from {co}")
sayHello("Jeff")
|
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
|
def multiplyBy5 (x):
return (x * 5)
print(multiplyBy5(5))
|
Empty function |
function emptyFunction {}
|
|
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.
|
Concept | PowerShell | Python |
Class with a fixed property |
Class Customer {
$Bank = "GlobalBank"
}
# Example usage:
$c = [Customer]::new()
$c.Bank
|
class Customer:
Bank = "GlobalBank"
# Example usage:
c = Customer()
print(c.Bank)
|
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
|
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)
|
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()
|
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)
|
|
Concept | PowerShell | Python |
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
|
|
Uninstall a module |
Uninstall-Module 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.
|
Concept | PowerShell | Python |
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()
|
Comments