You are on page 1of 5

Agenda

1. Looping
2. Conditionals
3. Regex

Looping

> $array = @("item1", "item2", "item3")

> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }


ite
m1
item2
item3

> $array = @("item1", "item2", "item3")

> foreach ($element in $array) { $element }


item1
item2
item3
> $array = @("item1", "item2", "item3")
$counter = 0;

while($counter -lt $array.length){


$array[$counter]
$counter += 1
}

item1
item2
item3

Conditions

If condition

$x = 10

if($x -le 20){


write-host("This is if statement")
}

If/else

$x = 30

if($x -le 20){


write-host("This is if statement")
}else {
write-host("This is else statement")
}
Nested if

$x = 30
$y = 10

if($x -eq 30){


if($y -eq 10) {
write-host("X = 30 and Y = 10")
}
}

Switch

switch(3){
1 {"One"}
2 {"Two"}
3 {"Three"}
4 {"Four"}
3 {"Three Again"}
}
Regular Expressions

#Format value
#Matches exact characters anywhere in the original value.
"book" -match "oo"

#Format .
#Logic Matches any single character.
"copy" -match "c..y"

#Format [value]
#Logic Matches at least one of the characters in the brackets.
"big" -match "b[iou]g"

#Format [range]
#Logic Matches at least one of the characters within the
range. The use
# of a hyphen (-) allows you to specify an adjacent
character.
"and" -match "[a-e]nd"

#Format [^]
#Logic Matches any characters except those in brackets.
"and" -match "[^brt]nd"

#Format ^
#Logic Matches the beginning characters.
"book" -match "^bo"

#Format $
#Logic Matches the end characters.
"book" -match "ok$"

#Format *
#Logic Matches any instances of the preceding character.
"baggy" -match "g*"

#Format ?
#Logic Matches zero or one instance of the preceding
character.
"baggy" -match "g?"
Example Script to create Log File

function Write-Log {
Param(
$Message,
$Path = "$env:USERPROFILE\log.txt"
)

function TS {Get-Date -Format 'hh:mm:ss'}


"[$(TS)]$Message" | Tee-Object -FilePath
$Path -Append | Write-Verbose
}

Write-Log 'Some message'

[10:58:43]Some message
[10:58:57]Some message
[10:58:59]Some message
[10:59:06]Some message

You might also like