<interpreter> <scriptfile>
pwsh example.ps1
, python example.py
./example.ps1
or ./example.sh
pwsh
from a shell/command
promptInstall both PowerShell & Python
Open pwsh
Type $PSVersionTable
Run python
(*nix python3
)
Look for version number
Type quit()
Write-Host 'Hello World'
print('Hello World')
.ps1
, Python .py
PowerShell
.\myscript.ps1 # Inside PowerShell
pwsh myscript.ps1 # From another shell (e.g. Bash)
Python
python3 myscript.py
How did you do it?
# powershell
$MyVar = 1
Write-Host $MyVar
1
# python
my_var = 2
print(my_var)
2
PowerShell
$MyString = 'Hello there'
Write-Host $MyString
Hello there
Write-Host MyString
MyString
Python
my_string = 'Hello there'
print(my_string)
Hello there
print('my_string')
my_string
PowerShell
$Num = 6
$Num = 66.342
## NOT
$Num = '6' # This is a string
Python
num = 6
num = 123.456
## NOT
num = '6' # This is also a string
$true
or $false
True
or False
bool
PowerShell
$MyBool = $true
$MyBool = $false
$MyBool = 'true' # NOT a boolean, just the word true
Python
my_bool = True
my_bool = False
my_bool = 'true' # NOT a boolean
my_bool = true # Will (probably) throw an error
$MyArr[0]
or my_list[6]
$MyArr.length
, len(my_list)
$MyArr[9]
my_list[0:10]
, my_list[2:]
or $MyArr[0..10]
PowerShell
# Create an empty array
$MyArr = @()
# Create an array with items
$MyArr = @(
'one',
'two',
3
)
$MyArr = 'one', 'two', 3
# Can access specific items
$MyArr[1]
two
# Can add items to the list
$MyArr = $MyArr + 'four'
$MyArr
one
two
3
four
Python
# Create an empty array
my_arr = []
# Create an array with items
my_arr = [
'one',
'two',
3
]
# Can access specific items
my_arr[1]
'two'
# Can add items to the list
my_arr.append('four')
my_arr
['one', 'two', 3, 'four']
['element']
.element
$MyHash['new'] = 'Something'
PowerShell
# Can declare empty hashtable
$MyHash = @{}
# Can declare with items
$MyHash = @{
one = 1
two = 2
three = 3
}
$MyHash['one']
1
$MyHash['four'] = 4
$MyHash
Name Value
---- -----
one 1
three 3
two 2
four 4
Python
# Can declare empty hashtable
my_dict = {}
# Can declare with items
my_dict = {
'one': 1,
'two': 2,
'three': 3
}
my_dict
{'one': 1, 'two': 2, 'three': 3}
my_dict['four'] = 4
my_dict
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
.element
, e.g. $MyObj.Name
$null
or None
to
see if it has been assigned a value[string] $MyVar
or [int] $MyVar
str(my_var)
or int(my_var)
Hint: The last item in a List/Array can be accessed with the index -1
Write a script in Python which does the following:
How did you do it?
type(var_name)
or $VarName.GetType()
isinstance(var_name, str)
and $Var -is 'String'
PowerShell
$a = 5
$b = 0.5
$a + $b
5.5
$a - $b
4.5
$a * $b
2.5
$a = '5'
$b = '0.5'
$a + $b
50.5
Python
a = '5'
b = '0.5'
a + b
'50.5'
a - b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
PowerShell
$a = @(1,2,3,4)
$b = @(5,6,7,8)
$a + $b
1
2
3
4
5
6
7
8
## Result = Arrays are combined
$a = @{one = 1; two = 2}
$b = @{three = 3; four = 4}
$a + $b
Name Value
---- -----
three 3
two 2
four 4
one 1
## Result = Hashtables are combined
Python
a = [1,2,3,4]
b = [5,6,7,8]
a + b
[1, 2, 3, 4, 5, 6, 7, 8]
## Result = Lists are combined
a = {'one':1, 'two':2}
b = {'three':3, 'four':4}
a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
## Result = ERROR!
Evaluate: 1 + 2 - 3 * 4 / 5
((1 + 2) - (3 * 4)) / 5
$i++
means add 1 to variable ‘i’var--
means subtract 1 from
variable ‘var’$var += 10
means $var = $var + 10
$i++
and ++$i
$a = $b++
means assign $a the value of $b, THEN increase $b
by 1$a = ++$b
means increase $b by 1, THEN assign $a the value
of $bComparison | PowerShell Operator | Python Operator |
---|---|---|
Equals | -eq | == |
Not Equals | -ne | != |
Greater than | -gt | > |
Less than | -lt | < |
Greater than or equal to | -ge | >= |
Less than or equal to | -le | <= |
In Array/List | -in | in |
Not In Array/List | -notin | not in |
Regex match | -match |
$var -gt 0 -or $var -lt 100
No parentheses necessary but ideally ($var -gt 0) -or ($var -lt 100)
$var -gt 0 -or $var -lt 100 -and $var -le 10
is ambiguous
so parentheses are required($var -gt 0 -or $var -lt 100) -and $var -le 10
PowerShell
if($var -eq $true){
Write-Host 'var is true'
}
Python
if var == True:
print('var is true')
PowerShell
if($var -eq $true){
Write-Host 'var is true'
}
else{
Write-Host 'var is not true'
}
else
keyword follows closing curly brace (generally on new
line)if
or else
enclosed in curly braces. Indent
is optionalPython
if var == True:
print('var is true')
else:
print('var is not true')
else
keyword on new line beneath if
result. NOT
indented, but requires colon (:)if
or else
MUST be indentedWrite a Python script which performs the following:
Change your list in such a way that you see what happens in both scenarios.
Write a PowerShell script which performs the following:
Hints:
- You can concatenate strings while printing, but it might be easier to create a new variable and print that
- Within an If or Else block you can have as many lines/commands as you wish. Remember, though, that each command should be on its own line
How did you do it?
else
but not requiredPowerShell
if($var -eq 10){
Write-Host 'var is 10'
}
elseif($var -gt 10){
Write-Host 'var is greater than 10'
}
else{
Write-Host 'var is less than 10'
}
elseif
keyword behaves exactly as if
does, but
MUST follow if
blockelseif
statement does not need to compare same variable(s)
as if
. Can be completely differentPython
if var == 10:
print('var is 10')
elif var > 10:
print('var is greater than 10')
else:
print('var is less than 10')
elif
(note spelling diff) behaves exactly as if
does.
MUST follow if
block and is NOT indentedelif
statement followed by colon (:)elif
statement can compare anything, as in PowerShellPowerShell
$MyVar = $false
if($MyVar -ne $true){
## Do something
}
Python
var = 10
if var >= 10:
print('var is big')
elif var > 5:
print('var is medium')
else:
print('var is small')
var is big
var = 10
if var >= 10:
print('var is big')
if var > 5:
print('var is medium')
else:
print('var is small')
var is big
var is medium
PowerShell
$Var = 10
if($Var -gt 10){
Write-Host 'Var is big'
}
if($Var -eq 10){
Write-Host 'Var is 10'
}
else{
Write-Host 'Var is small'
}
Var is small
if
has no else
so if it does not match,
nothing happensif
is evaluated and found to be true, so we execute
that code block, even though there is an else
below the 1st if
Write a PowerShell script which performs the following:
Hint: Finding if a number is multiple of 2 or 5 can be performed using the modulus % math operator
If/Else
$day = 3
if ( $day -eq 0 ) { $result = 'Sunday' }
elseif ( $day -eq 1 ) { $result = 'Monday' }
elseif ( $day -eq 2 ) { $result = 'Tuesday' }
elseif ( $day -eq 3 ) { $result = 'Wednesday' }
elseif ( $day -eq 4 ) { $result = 'Thursday' }
elseif ( $day -eq 5 ) { $result = 'Friday' }
elseif ( $day -eq 6 ) { $result = 'Saturday' }
else { $result = '?' }
$result
Switch
$day = 3
switch ( $day )
{
0 { $result = 'Sunday' }
1 { $result = 'Monday' }
2 { $result = 'Tuesday' }
3 { $result = 'Wednesday' }
4 { $result = 'Thursday' }
5 { $result = 'Friday' }
6 { $result = 'Saturday' }
default { $result = '?' }
}
$result
If / Else
day = 3
if day == 0:
result = "Sunday"
elif day == 1:
result = "Monday"
elif day == 2:
result = "Tuesday"
elif day == 3:
result = "Wednesday"
elif day == 4:
result = "Thursday"
elif day == 5:
result = "Friday"
elif day == 6:
result = "Saturday"
else:
result = "?"
print(result)
Match
day = 3
match (day):
case 0:
result = "Sunday"
case 1:
result = "Monday"
case 2:
result = "Tuesday"
case 3:
result = "Wednesday"
case 4:
result = "Thursday"
case 5:
result = "Friday"
case 6:
result = "Saturday"
case _:
result = "?"
print(result)
for
and while
continue
can skip the rest of an interationbreak
can break out of the loop if requiredif
, in terms of braces, colons &
indentPowerShell
$v = 0
while($v -lt 10){
Write-Host $v
$v++
}
Python
v = 0
while v < 10:
print(v)
v += 1
while
in
methodPowerShell
$MyArr = @(1,2,3,4,5)
for($i = 0; $i -lt $MyArr.count; $i++){
Write-Host $MyArr[$i]
}
for
keyword in Python, foreach
keyword in PowerShellPowerShell
$MyArr = @(1,2,3,4,5)
foreach($Item in $MyArr){
Write-Host $Item
}
Python
my_arr = [1,2,3,4,5]
for item in my_arr:
print(item)
continue
will skip the rest of the iteration and move on to
the next one. Useful if you wish to skip specific conditionsbreak
will stop the loop entirely. Useful if you have found
what you are looking forPowerShell
$MyArr = @(1,2,3,4,5)
foreach($Item in $MyArr){
Write-Host $Item
break
}
Python
my_arr = [1,2,3,4,5]
for item in my_arr:
if item == 2:
continue
print(item)
Write a Python script which performs the following:
Hint: You can convert a Python string to upper by using
var.upper()
Add to your script from the previous exercise the following:
Hint: Maybe use a
while
loop?
How did you do it?
PowerShell
# As array
$Contents = Get-Content myfile.txt
$Contents.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
# As string
$Contents = Get-Content myfile.txt -Raw
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
Python
with open('myfile.txt', 'r') as f:
contents = f.read()
type(contents)
<class 'str'>
Write a PowerShell script to load the contents of the file products.txt
and
print each item with a prefix of 'ProductID: ’
Hint:
Get-Content
will automatically convert a file to an Array of strings, one per line. If you want to load a whole file as a single string useGet-Content -Raw
How did you do it?
PowerShell
$Rows = Import-CSV myfile.csv -Delimiter ',' # If using comma -Delimiter can be omitted
# Show the 3rd item
$Rows[2]
# Show the 'map' attribute of the 5th item
$Rows[4].map
Python
import csv # You need to use a Python module for this
with open('myfile.csv', 'r') as f:
reader = csv.DictReader(f, delimiter=',') # If using comma delimiter=',' can be omitted
# Cast to list
rows = list(reader)
# Show the 3rd item
rows[2]
# Show the 'map' attribute of the 5th item
rows[4]['map']
Write a Python script to load the contents of the file edgehostnames.csv
and
print the recordName attribute of all lines whose ‘securityType’ attribute
is ‘STANDARD-TLS’
Hint: You will likely need to use a
for
loop and anif
condition to achieve this
How did you do it?
PowerShell
$JSON = Get-Content myfile.json -Raw
$Data = ConvertFrom-Json $JSON
# Show propertyName attribute
$Data.propertyName
myproperty
# Show 3rd child rule,
$Data.rules.children[2].Name
my child rule
Python
import json # You need to use a Python module for this
with open('myfile.json', 'r') as f:
data = json.load(f)
# Show propertyName attribute
data['propertyName']
'myproperty'
# Show 3rd child rule,
data['rules']['children'][2]['name']
'my child rule'
Write a PowerShell script to load the property.json
file and
print the origin hostname
Hint: The origin behaviour is the first item in the
behavior
Array/List, which is a member of therules
Object at the top of the json.
Hint:
hostname
is a member of theoptions
Dictionary/Object inside the behaviour
Remember: Reading the json file in a text editor is NOT cheating!
How did you do it?
function
in PowerShell, def
in
Python{}
(Powershell) or indented
(Python)return
statement (not required)function add($var1, $var2){
return $var1 + $var2
}
def add(var1, var2):
return var1 + var2
function add($var1, $var2){
return $var1 + $var2
}
add 1 2
3
add 3 4
7
add 'hello ' 'there'
hello there
def add(var1, var2):
return var1 + var2
add(1, 2)
3
add('hello ', 'there')
hello there
Write a Python script with a function named TellMeWhy which prints the line ‘tell me why I don’t like…’ then on the next line the input to the function. Call this function at least twice with different days of the week.
Note: Your function doesn’t need a
return
statement in this case
How did you do it?
global
function MyNameIs(){
$Name = 'Who?'
Write-Host "My Name is $Name"
}
$Name = 'What?'
MyNameIs
# What will the result be?
function MyNameIs($MyName){
Write-Host "My Name is $MyName"
}
$Name = 'Marshall'
MyNameIs -MyName $Name
function MyNameIs($MyName){
$Name = $MyName
}
$Name = 'Jim'
MyNameIs -MyName 'Bob'
Write-Host $Name
# What will the result be?
function MyNameIs($MyName){
return "My name is $MyName"
}
$Name = 'Jim'
$Name = MyNameIs -MyName 'Bob'
Write-Host $Name
# What will the result be?
def param_order(a, b, c):
print('The first param is {first}, the second is {second} and the third {third}'.format(first = a, second = b, third = c))
param_order('one', 'two', 'three')
The first param is one, the second is two and the third three
param_order('three', 'two', 'one')
The first param is three, the second is two and the third one
param_order(a = 'two', c = 'one', b = 'three')
The first param is two, the second is three and the third one
Param()
block
for more complexfunction Param-Order{
Param(
$a,
[string] $b,
[Parameter(Mandatory=$true)] [string] $c
)
Write-Host "Param a = $a, param b = $b, param c = $c"
}
Param-Order -a 'one' -b 'two' -c 'three'
Param a = one, param b = two, param c = three
Param-Order -a 'one' -b 'two'
cmdlet Param-Order at command pipeline position 1
Supply values for the following parameters:
c:
Write a PowerShell script which defines a function called combine
.
This function should take 3 parameters. Each parameter should be made part
of a string of the form 'Parameter 1:
Note: The Write-Host command must be outside the function
How did you do it?
{
"name": "top",
"children": [
{
"name":"child",
"children": [
{
"name":"grandchild",
"children": [ ]
}
]
}
]
}
$Data = Get-Content myjson.json | ConvertFrom-Json -Depth 10
function recurse($Parent){
foreach($child in $Parent.children){
recurse($child)
}
Write-Host $Parent.name
}
recurse $Data.rules
Write a script in PowerShell which loads the file property.json
and
recurses through all rules under the top-level rules
object,
printing the name, comments (if any) and how many children are present
in the rule.
Where-Object
& Python list comprehension commonresults = []
for line in data:
if line['record'] == 'something I want':
results.append(line)
$Results = @()
foreach($Line in $Data){
if($Line.record -eq 'something I want'){
$Results += $Line
}
}
Where-Object
used to filter objects by valueWhere-Object
aliases: where
or even ?
Where-Object
uses $_
as a variable
to represent each object that is being checkedSelect-Object
then used to select attributes you are interested
inSelect-Object
alias: select
Sort-Object
sorts lists by specific object memberSimple
<Object to be filtered>
| <where|?|Where-Object>
$EdgeHostnames | Where-Object recordName -eq www.example.com
$EdgeHostnames | ? ttl -ne 21600
Complex
<Object to be filtered>
| <where|?|Where-Object>
{
$EdgeHostnames | Where-Object { $_.recordName -eq www.example.com }
$EdgeHostnames | Where-Object { $_.recordName.contains('www') -or $_.dnsZone -eq 'edgesuite.net' }
<Object to be filtered> | Select <attribute1>, <attribute 2>
$EdgeHostnames | Select-Object recordName, EdgeHostnameID
Sort-Object
can use a specific
property to sort$MyList | Sort-Object
$MyList | Sort-Object -Descending
$MyList | Sort-Object -Property Name
Where-Object
and Select-Object
can return $null
if
nothing matchesWrite a powershell script which performs the following:
Use any filtering method you prefer
How did you do it?
filter()
function takes input object and function to filtersort()
function sorts a list in-place and updates the variableNote:
sort()
does not return the sorted list!
[ <element> for <element> in <List to filter> if <condition>]
results = [ member for member in data if member['something'] == 'something I want']
lambda
in-line functionsdef myFilter(argument):
if argument > 1:
return True
else:
return False
results = filter (myFilter, data)
More commonly…
results = filter( lambda a: a > 1, data)
my_list = [5,3,2,4,1]
my_list.sort()
print(my_list)
[1,2,3,4,5]
Write a Python script which performs the following:
Use any filtering method you prefer
Read-Host
, and you can supply a -Prompt
param
to help the user (best practice)input()
, and you can supply a string param to
the function to help the user, e.g. input('Please input your name:')
$InputVariable = Read-Host -Prompt 'What is your name?'
Write-Host $InputVariable
.\prompt.ps1
What is your name?: Stuart
Stuart
input_variable = input('What is your name?')
print(input_variable)
python prompt.py
What is your name?Stuart
Stuart
param(
[Parameter(Mandatory=$true)] [string] $Name
)
Write-Host "Hi, my name is $Name"
./myscript.ps1 -Name 'Stuart'
Hi, my name is Stuart
./myscript.ps1
cmdlet myscript.ps1 at command pipeline position 1
Supply values for the following parameters:
Name:
param(
[Parameter(Mandatory=$false)] [string] $Name = 'Slim Shady'
)
Write-Host "Hi, my name is $Name"
./myscript.ps1
Hi, my name is Slim Shady
Write a PowerShell script with 4 parameters of various types, where the first 2 are mandatory but the 3rd and 4th are optional. Your script should prompt the user for a further piece of information, then print all 5 options (supplied or not) in some way.
Note: Execute your script using named parameters, rather than waiting for the script to prompt you (except for the deliberate prompt)
How did you do it?
sys.argv
- List of script params, first is the
name of the scriptargparse
Click
, but is more complex to implement (though
a lot cooler)import sys
print(str(sys.argv))
print(sys.argv[1])
python myscript.py arg1 arg2 arg3
['myscript.py', 'arg1', 'arg2','arg3']
'arg1'
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--simple', action='store', dest='simple_value',
help='Store a simple value')
parser.add_argument('-t', action='store_true', default=False,
dest='boolean_switch',
help='Set a switch to true')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
results = parser.parse_args()
print('simple_value =', results.simple_value)
print('boolean_switch =', results.boolean_switch)
$ python args.py -h
usage: arg.py [-h] [-s SIMPLE_VALUE] [-t] [--version]
options:
-h, --help show this help message and exit
-s SIMPLE_VALUE Store a simple value
-t Set a switch to true
--version show program's version number and exit
Recreate your script from the previous exercise, except this time in Python
using argparse
and input()
Note: It’s probably better to get aruments from the script invocation than using
input()
, but it is still valid
How did you do it?
Get-Help
can be run on any function or script<#
.DESCRIPTION
This script adds 2 things together
.SYNOPSIS
Add 2 inputs
.EXAMPLE
> .\script.ps1 -Input1 1 -Input2 2
.PARAMETER Input1
The first input
.PARAMETER Input2
The second parameter
.LINK
http://scriptclub.edgesuite.net
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[int]
$Input1,
[Parameter()]
[int]
$Input2
)
# Print out 2 inputs added together
$Result = $Input1 + $Input2
return $Result
> Get-Help .\script.ps1
NAME
C:\code\scriptclub\exercises\script.ps1
SYNOPSIS
Add 2 inputs
SYNTAX
C:\code\scriptclub\exercises\script.ps1 [-Input1] <Int32> [[-Input2] <Int32>] [<CommonParameters>]
DESCRIPTION
This script adds 2 things together
RELATED LINKS
http://scriptclub.edgesuite.net
REMARKS
To see the examples, type: "Get-Help C:\code\scriptclub\exercises\script.ps1 -Examples"
For more information, type: "Get-Help C:\code\scriptclub\exercises\script.ps1 -Detailed"
For technical information, type: "Get-Help C:\code\scriptclub\exercises\script.ps1 -Full"
For online help, type: "Get-Help C:\code\scriptclub\exercises\script.ps1 -Online"
Rewrite your PowerShell script from exercise 1 and add comment-based help.
Run Get-Help
with the basic options, and also with -Detailed
and -Full
parameters.
How did you do it?
return
statement in scripts behaves just as it does in functionsreturn
would never execute (editor may show
this)param(
[string] $FirstElement,
[string] $SecondElement
)
return @{ first = $FirstElement; second = $SecondElement }
$Result = combine.ps1 -FirstElement hello -SecondElement there
$Result
Name Value
---- -----
first hello
second there
$Result.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Hashtable System.Object
Write a PowerShell script takes in 5 strings, sorts them alphabetically and returns them as an Array. Assign the result to a variable in your shell then print it. Do not print within the script.
How did you do it?
Out-File
, Set-Content
or Add-Content
with open()
and set mode to w
(write)
or a
(append)write()
writes strings, writelines()
writes listswritelines()
will NOT add line breaks to your file,
but PowerShell Out-File
will$MyList = @(1,2,3,4,5)
$MyList | Out-File mylist.txt
my_string = 'To be, or not to be'
with open('mystring.txt', 'w') as f:
f.write(my_string)
my_list = ['To','be,\n','or ','not ','to ','be']
with open('mylist.txt', 'w') as f:
f.writelines(my_list)
Export-CSV
automaticallydata_list = [] # List of Dicts
with open('mycsv.csv', 'w', encoding='utf8', newline='') as output_file:
fc = csv.DictWriter(output_file, fieldnames=data_list[0].keys(),)
fc.writeheader()
fc.writerows(data_list)
$MyArray = @() # List of objects/hashtables
$MyArray | Export-CSV mycsv.csv
Write a script in Python which reads the file edgehostnames.csv. Change any value and write the result to a new CSV file
How did you do it?
dump()
(write
file) and dumps()
convert to json string
indent=2
or indent=4
to prettify output
if requiredConvertTo-Json
and pipe to Out-File
or Set-Content
.
Likely need to set -Depth
if your file is heavily nestedimport json
my_dict = {} # Dictionary populated with data
with open('myjson.json', 'w') as f:
json.dump(my_dict, f, indent=2)
$MyObject = @{} #Hashtable or Object with data
$MyObject | ConvertTo-Json -Depth 10 | Out-File myjson.json
Write a script in PowerShell which loads the file property.json and converts it to a PowerShell object. Change the propertyName top-level attribute and write the resulting object to a new json file
How did you do it?
try
blockthrow
statementscatch
blockstry
blocks must have a corresponding catch
blocktry{
1 / 0
}
catch{
Write-Host 'An error has occured. Nuts.'
}
try
,
but if one throws an error, the rest will be skipped$_
function MakeError($Fail){ if($fail){ throw 'Awww, shucks' } }
try{
Write-Host 'Before the error'
MakeError $true
Write-Host 'After the error'
}
catch{
Write-Host 'An error has occured'
Write-Host $_
}
throw
keyword-ErrorAction stop
$SomeVariable = Read-Host 'Enter a number greater than 0'
if($SomeVariable < 0){
throw 'Variable is invalid'
}
Write a function in PowerShell which generates a random number between
1 and 10 (use Get-Random
). If the number is greater than 5,
throw an error. Call your function in the script without try/catch, and
finish with a Write-Host command to show you have reached the end. Note
what happens when the script fails.
Next, update your script to call your function inside a try/catch block such that an errors are handled gracefully, and finish with a Write-Host command to show you have made it to the end of the script.
How did you do it?
try
blockexcept
blocks, which typically
create an error variable (except <type> as <variable>
)import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error:", err)
except ValueError:
print("Could not convert data to an integer.")
except Exception as err:
print(f"Unexpected {err=}, {type(err)=}")
raise
function, which takes an error type an information
string as argumentimport re
some_variable = input('Enter a number greater than 0: ')
if not re.match('^\-?[\d]{1}$', some_variable):
raise Exception('Only numbers are acceptable')
if int(some_variable) < 0:
raise ValueError('Number must be positive')
print('Made it to the end')
Write a function in Python which takes 2 inputs, and subtracts the 2nd from the 1st. Call your function without try/except and note what happens when you use variables which cannot be subtracted (e.g. string, List). Add a print() command at the end to show you have reached the end of the script.
Next, edit your script to raise an error if either input is not an integer, and wrap your function calls in try/except to see what happens when an error occurs.
How did you do it?
pip
import requests
r = requests.get('https://httpbin.org/get?hello=world')
print(r.text)
import requests
payload = {
'hello': 'world'
}
r = requests.post('https://httpbin.org/post', json=payload)
print(r.text)
import requests
url = 'https://httpbin.org/headers'
headers = {
'User-Agent': 'ScriptClub'
'Mastery-Level': 'Expert'
}
response = requests.get(url, headers = headers)
data = response.json()
print(response.status_code)
print(data['headers']['Mastery-Level'])
Write a script in Python which makes a call to https://httpbin.org/headers and includes a custom If-Modified-Since header and 3 request cookies. Use the json() function to convert your response, then print the names and values of each of the 3 cookies on their own line.
Hint: Cookies are sent in a single request header, and will be combined in the response, so you will need to split them to an array and loop through it.
How did you do it?
Invoke-WebRequest
contains lots more information than Invoke-RestMethod
,
but Invoke-RestMethod
probably the more common to useInvoke-RestMethod
Response automatically converted to Object
from JSON (if applicable), but does not contain status code, or some other
aspects$1 = Invoke-WebRequest -Uri 'https://httpbin.org/get?hello=world'
$1
$2 = Invoke-RestMethod -Uri 'https://httpbin.org/get?hello=world'
$2
-Body
is a String parameter, unlike json
in Python
requests (dict
)$Headers = @{
'User-Agent' = 'ScriptClub'
'Mastery-Level' = 'Expert'
}
$Payload = '{
"hello": "world"
}'
$Response = Invoke-RestMethod -Uri 'https://httpbin.org/post' -Method Post -Headers $Headers -Body $Payload -ResponseHeadersVariable ResponseHeaders
$Response
$ResponseHeaders
Convert your previous script from Exercise 1 into PowerShell. You may
use either Invoke-RestMethod
or Invoke-WebRequest
as
you see fit, but you must print the Server
response header.
How did you do it?
pip
or pip3
executable typically installed with
your Python installpython -m pip
python -m pip install <module name>
python -m pip install <module name>==<version>
requirements.txt
,
and installed with python -m pip install -r requirements.txt
requirements.txt
can contain just names, or also specific
or minimum versions denoted by ==
, >=
etc.Look up the latest version of the following Python modules: requests, edgegrid-python & xlsxwriter. Create a requirements.txt file specifying these versions (either exactly or at a minimum) and install them onto your laptop.
If you already have one of these modules installed at its maximum version, pick a different one
How did you do it?
pip
, external modules can be installed
with a single command, Install-Module
~/Documents/PowerShell/Modules
(CurrentUser)C:\Program Files\PowerShell\Modules
(AllUsers)$HOME/.local/share/powershell/Modules
(CurrentUser)/usr/local/share/powershell/Modules
(AllUsers)Create a text file or csv with the names and latest versions of the following PowerShell modules: AWSPowershell, AkamaiPowerShell and ImportExcel. Write a PowerShell script to load this file and install each of the modules.
You should run the following command first:
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
. This will prevent prompts during installation of the modules
requests
(and derivatives)pip
package, python -m pip install edgegrid-python
session
objectimport requests
from akamai.edgegrid import EdgeRc, EdgeGridAuth
session = requests.Session()
#Inline
session.auth = EdgeGridAuth(
client_token='akab-fp5z3sp714x155hr-mv7hrcu7j4iohgl9',
client_secret='tQi7/x5DbFoZG7Ojv62AQ2U0iBOEpzTlHn07KeYpyZs=',
access_token='akab-rba8e9xa19gxbttd-rtyjm0rhcynqfslf'
)
hostname = 'akab-s1xcwas8oesoh43d-6rb2dj3zcusyr9zf.luna.akamaiapis.net'
## OR from EdgeRC
edgerc = EdgeRc('~/.edgerc')
section = 'default'
hostname = edgerc.get(section, 'host')
session.auth = EdgeGridAuth.from_edgerc(edgerc, section)
response = session.get('https://' + hostname + '/papi/v1/contracts')
Install the edgegrid-python pip (if you don’t already have it). Write a Python script to list all groups in a given contract (any customer account will do). Filter the group to find a specific one, then with that groupId and contractId list all properties in that group. Print the names of all properties you find.
Hint: Finding the right API endpoint can be tricky sometimes. Feel free to ask if it is not immediately obvious which one to use
How did you do it?
Install-Module AkamaiPowershell
Get-Property
, New-AppSecConfiguration
-EdgeRCFile
, -Section
, -AccountSwitchKey
#PAPI
$Rules = Get-PropertyRuleTree -PropertyName MyProperty -PropertyVersion latest -AccountSwitchKey 1-6JHGX:1-8BYUX
$Rules.rules.behaviors.options.hostname = 'neworigin.example.com'
$Rules | Set-PropertyRuleTree -PropertyName MyProperty -ProeprtyVersion latest -AccountSwitchKey 1-6JHGX:1-8BYUX
#AppSec
Set-AppSecPolicyAttackGroup -ConfigName smacleod -VersionNumber latest -PolicyName ion.stuartmacleod.net -AttackGroupID SQL -Action deny -AccountSwitchKey 1-6JHGX:1-8BYUX
#EdgeWorkers
New-EdgeWorkerVersion -Name smacleod_ew1 -CodeDirectory . -AccountSwitchKey 1-6JHGX:1-8BYUX
Install the AkamaiPowershell module (if you don’t already have it). Write a PowerShell script to list all cloudlet policies in a given account. Use that data to find a specific Edge Redirector policy, pull down the most recent version and print out the total number of rules it contains.
Hint: In PowerShell (as in the API) Shared cloudlet policies (v3) use different commands than regular (v2) ones. PowerShell also has a LOT of different commands, so feel free to ask for help in choosing the right command.
#
for single lines, but differs between
languages# This comment describes what this function is doing
<#
This is a
multi-line comment
#>
# So
# Is
# This
# Single comments use hash
"""
This is technically a multi-line string,
but if not assigned to a variable, Python will ignore it.
Just like a comment.
"""
}
(see indentation)$Files = Get-ChildItem; foreach($File in $Files){ Write-Host $File.Name }; Write-Host 'Complete'
# Is the same as
$Files = Get-ChildItem
foreach($File in $Files){
Write-Host $File.Name
}
Write-Host $Complete
if($Something -eq 10){
Write-Host 'Top'
foreach($Item in $MyArray){
Write-Host 'Middle'
while($Item -gt 5){
Write-Host 'Bottom'
}
}
}
if($Something -eq 10){
Write-Host 'Top'
foreach($Item in $MyArray){
Write-Host 'Middle'
while($Item -gt 5){
Write-Host 'Bottom'
}
}
}
(Helpful info below…)
edgegrid-python
or AkamaiPowershell
are required