Script Language Syntax
Last updated
Last updated
TODO: need syntax examples for Bash and Windows Batch scripting (issue #22)
Add syntax examples for Bash and Windows Batch scripting
Add example output for all
TODO: Add other operator types
References
If you like this content and would like to see more, please consider buying me a coffee!
Type
Code Examples
Standard Variable
var = "Hello"
Global Variable
global var
var = "Hello"
Environment Variables
Retrieving Variable Contents
Type
Code Examples
Standard Variable
$var = "Hello"
Global Variable
$global:var = "Hello"
Environment Variables
Retrieving Variable Contents
Type
Code Examples
Standard Variable
Global Variable
Environment Variables
Retrieving Variable Contents
Type
Code Examples
Standard Variable
Global Variable
Environment Variables
Retrieving Variable Contents
Method
Code Examples
Normal String
"Hello World"
'Hello World'
Empty String
""
''
Multiline String
"""Hello
World"""
Select Character from String
str = 'Hello'
str[1]
# 'e'
Get Length
str = 'Hello'
len(str)
# 5
Remove whitespace at front and back
str = ' Hello World '
str.strip()
# 'Hello World'
To Lowercase
str = 'HELLO WORLD'
str.lower()
# 'hello world'
To Uppercase
str = 'hello world'
str.upper()
# 'HELLO WORLD'
Replace
str = 'Hello'
str.replace('H', 'Y')
# 'Yello'
Split
str = 'Hello, World'
str.split(',')
# ['Hello', ' World']
Join
list = ["Hello", "World"]
", ".join(list)
# 'Hello World'
Formatting
price = 42
txt = "The price is {} dollars"
print(txt.format(price))
# The price is 42 dollars
Formatting by Index
price = 42
txt = "The price is {0} dollars"
print(txt.format(price))
# The price is 42 dollars
Formatting Strings
price = 42
f"The price is {price} dollars"
# The price is 42 dollars
Method
Code Examples
Normal String
"Hello World"
'Hello World'
Empty String
""
''
Multiline String
"Hello
World
"
Select Character from String
$str = 'Hello'
$str[1]
# e
Get Length
$str = 'Hello'
$str.Length
# 5
Remove whitespace at front and back
$str = ' Hello World '
$str.Trim()
# 'Hello World'
To Lowercase
$str = 'HELLO WORLD'
$str.ToLower()
# hello world
To Uppercase
$str = 'hello world'
$str.ToUpper()
# HELLO WORLD
Replace
$str = 'Hello'
$str.Replace('H', 'Y')
# Yello
Split
'Hello, World' -split ','
# @('Hello', ' World')
Join
$array = @("Hello", "World")
$array -join ", "
[String]::Join(', ', $array)
# Hello World
Formatting
$price = 42
$txt = "The price is {0} dollars"
$txt -f $price
# The price is 42 dollars
Formatting by Index
$price = 42
$txt = "The price is {0} dollars"
$txt -f $price
# The price is 42 dollars
Formatting Strings
$price = 42
$txt = "The price is $price dollars"
# The price is 42 dollars
Method
Code Examples
Normal String
Empty String
Multiline String
Select Character from String
Get Length
Remove whitespace at front and back
To Lowercase
To Uppercase
Replace
Split
Join
Formatting
Formatting by Index
Formatting Strings
${FOO:-val}
$FOO
, or val
if unset (or null)
${FOO:=val}
Set $FOO
to val
if unset (or null)
${FOO:+val}
val
if $FOO
is set (and not null)
${FOO:?message}
Show error message and exit if $FOO
is unset (or null)
${FOO%suffix}
Remove suffix
${FOO#prefix}
Remove prefix
${FOO%%suffix}
Remove long suffix
${FOO##prefix}
Remove long prefix
${FOO/from/to}
Replace first match
${FOO//from/to}
Replace all
${FOO/%from/to}
Replace suffix
${FOO/#from/to}
Replace prefix
${FOO:0:3}
Substring (position, length)
${FOO:(-3):3}
Substring from the right
${#FOO}
Length of $FOO
Method
Code Examples
Normal String
Empty String
Multiline String
Select Character from String
Get Length
Remove whitespace at front and back
To Lowercase
To Uppercase
Replace
Split
Join
Formatting
Formatting by Index
Formatting Strings
Type
Code Examples
As Integer
i = int("10")
As Float
i = float("10.5")
As String
i = str(10)
As Char
Type
Code Examples
As Integer
$i = [int]"10"
As Float
$i = [float]"10.5"
As String
$i = [string]10
As Char
Type
Code Examples
As Integer
As Float
As String
As Char
Type
Code Examples
As Integer
As Float
As String
As Char
Activity
Code examples
Define
['Hello', 'World']
Access Elements
arr = ['Hello', 'World']
arr[0]
# 'Hello'
Get Length
arr = ['Hello', 'World']
len(arr)
Adding Elements
arr = ['Hello', 'the']
arr.append('World')
Removing Elements
arr = ['Hello', 'World']
arr.pop(1)
Remove Element by Value
arr = ['Hello', 'World']
arr.remove('Hello')
Activity
Code examples
Define
@('Hello', 'World')
Access Elements
$arr = @('Hello', 'World')
$arr[0]
# Hello
Get Length
$arr = @('Hello', 'World')
$arr.Length
Adding Elements
$arr = @('Hello', 'the')
$arr += "World"
Removing Elements
$arr = [System.Collections.ArrayList]@('Hello', 'World')
$arr.RemoveAt($arr.Count - 1)
Remove Element by Value
$arr = [System.Collections.ArrayList]@('Hello', 'World')
$arr.Remove("Hello")
Activity
Code examples
Define
Access Elements
Get Length
Adding Elements
Removing Elements
Remove Element by Value
Activity
Code examples
Define
Access Elements
Get Length
Adding Elements
Removing Elements
Remove Element by Value
Switch
Code Examples
If / ElseIf / Else
a = 42
b = 420
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")
Case
Switch
Code Examples
If / ElseIf / Else
$a = 42
$b = 420
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"
}
Case
Switch
Code Examples
If / ElseIf / Else
Case
Switch
Code Examples
If / ElseIf / Else
Case
Loop Type
Code Examples
For
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
While
i = 1
while i < 6:
print(i)
i += 1
Break
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Continue
i = 1
while i < 6:
print(i)
if i == 3:
continue
i += 1
Loop Type
Code Examples
For
$fruits = @("apple", "banana", "cherry")
foreach($x in $fruits)
{
Write-Host $x
}
While
$i = 1
while ($i -lt 6)
{
Write-Host $i
$i++
}
Break
$i = 1
while ($i -lt 6)
{
Write-Host $i
if ($i -eq 3)
{
break
}
$i++
}
Continue
$i = 1
while ($i -lt 6)
{
Write-Host $i
if ($i -eq 3)
{
continue
}
$i++
}
Loop Type
Code Examples
For
While
Break
Continue
Loop Type
Code Examples
For
While
Break
Continue
Functions
Code Examples
Definition
def hello_function():
print("Hello from my function!")
<code></code>
hello_function()
Arguments
def my_name(fname, lname):
print("My name is " + fname + " " + lname)
<code></code>
my_function("Wolf", "Zweiler")
Variable Arguments
def second_arg(*children):
print("The youngest child is " + children[1])
<code></code>
my_function("Sarah", "Emily", "Tom")
Named Arguments
def young_child(child3, child2, child1):
print("The youngest child is " + child3)
<code></code>
my_function(child1 = "Sarah", child2 = "Emily", child3 = "Tom")
Default Values
def my_country(country = "Wakanda"):
print("I am from " + country)
<code></code>
my_country()
Return Values
def five_times(x):
return 5 * x
Functions
Code Examples
Definition
function hello_function()
{
Write-Host "Hello from my function!"
}
hello_function
Arguments
function my_name($fname, $lname)
{
Write-Host "My name is $fname $lname"
}
my-function -fname "Wolf" -lname "Zweiler"
Variable Arguments
function second_arg()
{
Write-Host "The youngest child is $($args[1])"
}
my-function "Sarah" "Emily" "Tom"
Named Arguments
function young_child($child3, $child2, $child1)
{
Write-Host "The youngest child is $child3"
}
my-function -child1 "Sarah" -child2 "Emily" -child3 "Tom"
Default Values
function my_country
{
param(
$country = "Wakanda"
)
<code></code>
Write-Host "I am from $country"
}
my_country
Return Values
function five_times($x)
{
5 * $x
}
Functions
Code Examples
Definition
Arguments
Variable Arguments
Named Arguments
Default Values
Return Values
$#
Number of arguments
$*
All arguments
$@
All arguments, starting from first
$1
First argument
$_
Last argument of the previous command
Functions
Code Examples
Definition
Arguments
Variable Arguments
Named Arguments
Default Values
Return Values
Activity
Code Examples
Class Definition
class MyClass:
x = 5
Object Creation
MyClass()
Using Class Constructors
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
<code></code>
p1 = Person("Bob", 42)
Defining and using Methods
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
<code></code>
def myfunc(self):
print("Hello my name is " + self.name)
<code></code>
p1 = Person("Bob", 42)
p1.myfunc()
Activity
Code Examples
Class Definition
class MyClass {
$x = 5
}
Object Creation
[MyClass]::new()
Using Class Constructors
class Person {
Person($Name, $Age) {
$this.Name = $Name
$this.Age = $Age
}
<code></code>
$Name = ''
$Age = 0
}
[Person]::new('Bob', 42)
Defining and using Methods
class Person {
Person($Name, $Age) {
$this.Name = $Name
$this.Age = $Age
}
<code></code>
[string]myfunc() {
return "Hello my name is $($this.Name)"
}
<code></code>
$Name = ''
$Age = 0
}
<code></code>
[Person]::new('Bob', 42)
Activity
Code Examples
Class Definition
Object Creation
Using Class Constructors
Defining and using Methods
Activity
Code Examples
Class Definition
Object Creation
Using Class Constructors
Defining and using Methods
Comment Type
Code Examples
Single line
# Hello, world!
Multiline
"""
Hello, world!
"""
Comment Type
Code Examples
Single line
# Hello, world!
Multiline
<#
Hello, world!
#>
Comment Type
Code Examples
Single line
Multiline
Comment Type
Code Examples
Single line
Multiline
Action
Code Examples
Get Object's Type
var = 1
type(var)
Action
Code Examples
Get Object's Type
$var = 1
$var | Get-Member
#or
$var.GetType()
Action
Code Examples
Get Object's Type
Action
Code Examples
Get Object's Type
Activity
Code Examples
Defining
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Elements
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict['brand']
Updating Elements
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict['brand'] = 'Chevy'
Enumerating Keys
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Enumerating Values
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
Check if key exists
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Adding items
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
Activity
Code Examples
Defining
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
Accessing Elements
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
$thisdict.brand
<code></code>
or
<code></code>
$thisdict['brand']
Updating Elements
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
$thisdict.brand = 'Chevy'
Enumerating Keys
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
$thisdict.Keys | ForEach-Object {
$_
}
Enumerating Values
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
$thisdict.Values | ForEach-Object {
$_
}
Check if key exists
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
if ($thisdict.ContainsKey("model"))
{
Write-Host "Yes, 'model' is one of the keys in the thisdict dictionary"
}
Adding items
$thisdict = @{
brand = "Ford"
model = "Mustang"
year = 1964
}
$thisdict.color = 'red'
Activity
Code Examples
Defining
Accessing Elements
Updating Elements
Enumerating Keys
Enumerating Values
Check if key exists
Adding items
Activity
Code Examples
Defining
Accessing Elements
Updating Elements
Enumerating Keys
Enumerating Values
Check if key exists
Adding items
Lambda
Code Examples
Lambda
x = lambda a : a + 10
print(x(5))
Lambda
Code Examples
Lambda
$x = { param($a) $a + 10 }
& $x 5
Lambda
Code Examples
Lambda
Lambda
Code Examples
Lambda
Operator
Code Examples
Addition
var = 1 + 1
Subtraction
var = 1 - 1
Multiplication
var = 1 * 1
Division
var = 1 / 1
Modulus
var = 1 % 1
Floor
var = 10 // 3
Exponent
var = 10 ** 3
Operator
Code Examples
Addition
$var = 1 + 1
Subtraction
$var = 1 - 1
Multiplication
$var = 1 * 1
Division
$var = 1 / 1
Modulus
$var = 1 % 1
Floor
$var = [Math]::Floor(10 / 3)
Exponent
$var = [Math]::Pow(10, 3)
Operator
Code Examples
Addition
Subtraction
Multiplication
Division
Modulus
Floor
Exponent
Operator
Code Examples
Addition
Subtraction
Multiplication
Division
Modulus
Floor
Exponent
Operator
Description
Example
+
Addition of two operands
1 + 2 will give 3
−
Subtracts second operand from the first
2 − 1 will give 1
*
Multiplication of both operands
2 * 2 will give 4
/
Division of the numerator by the denominator
3 / 2 will give 1.5
%
Modulus operator and remainder of after an integer/float division
3 % 2 will give 1
Operator
Description
Example
EQU
Tests the equality between two objects
2 EQU 2 will give true
NEQ
Tests the difference between two objects
3 NEQ 2 will give true
LSS
Checks to see if the left object is less than the right operand
2 LSS 3 will give true
LEQ
Checks to see if the left object is less than or equal to the right operand
2 LEQ 3 will give true
GTR
Checks to see if the left object is greater than the right operand
3 GTR 2 will give true
GEQ
Checks to see if the left object is greater than or equal to the right operand
3 GEQ 2 will give true
Operator
Description
AND
This is the logical “and” operator
OR
This is the logical “or” operator
NOT
This is the logical “not” operator
Operator
Description
Example
+=
This adds right operand to the left operand and assigns the result to left operand
Set /A a = 5
a += 3
Output will be 8
-=
This subtracts the right operand from the left operand and assigns the result to the left operand
Set /A a = 5
a -= 3
Output will be 2
*=
This multiplies the right operand with the left operand and assigns the result to the left operand
Set /A a = 5
a *= 3
Output will be 15
/=
This divides the left operand with the right operand and assigns the result to the left operand
Set /A a = 6
a/ = 3
Output will be 2
%=
This takes modulus using two operands and assigns the result to the left operand
Set /A a = 5
a% = 3
Output will be 2
Operator
Description
&
This is the bitwise “and” operator
|
This is the bitwise “or” operator
^
This is the bitwise “xor” or Exclusive or operator
p
q
p & q
p | q
p ^ q
0
0
0
0
0
0
1
0
1
1
1
1
1
1
0
1
0
0
1
1
Error Handling
Code Examples
Try/Except
try:
print(x)
except:
print("An exception occurred")
Else
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
Finally
try:
f = open("file.txt") f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
Raise
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
Error Handling
Code Examples
Try/Catch
try {
Write-Host $x
} catch {
Write-Host "An exception ocurred"
}
Error Handling
Code Examples
Try/Catch
Error Handling
Code Examples
Try/Catch
Activity
Code Examples
Install
pip install requests
Import
import requests
List
pip list
Activity
Code Examples
Install
Install-Module Pester
Import
Import-Module Pester
List
Get-Module -ListAvailable
Activity
Code Examples
Install
Import
List
Activity
Code Examples
Install
Import
List