Objects

Exploring Objects

Date Object

$dateobject = get-date
$dateobject

Exploring Properties

$dateobject.Day
$dateobject.DayOfWeek
$dateobject.Month

$dateobject.Day = $dateobject.Day+1

Exploring Methods

$dateobject.ToLongDateString()

$dateobject.AddDays(1)
$dateobject.AddMonths(-1)

What can I do with a specific object

$dateobject = get-date
get-member -InputObject $dateobject
get-date | get-member

On what kind of day was I born

function Tellme-MyBirthday {
    param( 
        [int]$day = 1,
        [int]$month = 1,
        [int]$year = 1980
    )
    $birthday = get-date -Day $day -Month $month -Year $year
    write-host ("You were born on a {0}" -f $birthday.DayOfWeek)
}
tellme-mybirthday -day 14 -month 4 -year 1986

Predict Monthly full

get-date -Minute 0 -Second 0 -Millisecond 0 -Hour 22 -day 1
function Predict-MonthlyFullDay {
    param( 
        [System.DayOfWeek]$weekday = "Saturday",
        [int]$week=1,
        [int]$nextmonths = 12
    )
    $startdate = (get-date -Minute 0 -Second 0 -Millisecond 0 -Hour 22 -day 1)

    if($week -lt 5 -and $week -gt 0) {
        for($i=1;$i -le $nextmonths;$i++) {
            $passedMatchingDay = 0
            $monthday = $startdate.AddMonths($i)
            while($passedMatchingDay -ne $week) {
                if($monthday.DayOfWeek -eq $weekday) {
                    $passedMatchingDay++
                } 

                if($passedMatchingDay -ne $week) {
                    $monthday = $monthday.AddDays(1)
                }
            }
            write-host $monthday.ToLongDateString()
        }
    } else {
        write-host "Not implemented"
    }
}
Predict-MonthlyFullDay -nextmonths 48 -week 2

String as an object

This is a string object

$str = "Hello this is a String "
$str | gm
$str.length
$str.trim()
$str.trim().length
$str.ToUpper()
$str.ToLower()
$str.IndexOf("this")
$str.IndexOf("that")
$str.ToCharArray()[6..9]
$str.ToCharArray()[6..9] -join ""

Convert string to byte array (get some ASCII)

[byte[]]$byteArray = "Hello".toCharArray()
$byteArray
[byte[]]$byteArray =  "алло".ToCharArray()

Compare to

[System.Text.Encoding]::Utf8.GetBytes("Hello")
[System.Text.Encoding]::Unicode.GetBytes("Hello")
[System.Text.Encoding]::Utf8.GetBytes("алло")
[System.Text.Encoding]::Unicode.GetBytes("алло")

Making your own objects

Making bob

$bob = New-Object -TypeName psobject -Property @{
    "FirstName"="Bob";
    "LastName"="Sinclair";
    "Score"=6;
    "Birthday"=(get-date -Minute 0 -Second 0 -Millisecond 0 -Hour 0 -Year 2003 -Day 1 -Month 3)
}
$bob.Score
$bob.Birthday
$bob

Making more students

function Make-Student {
    param(
        [string]$firstname="",
        [string]$lastname="",
        [int]$score=3,
        [int]$day = 1,
        [int]$month = 1,
        [int]$year = 2003

    )
    return New-Object -TypeName psobject -Property @{
    "FirstName"=$firstname;
    "LastName"=$lastname;
    "Score"=$score;
    "Birthday"=(get-date -Minute 0 -Second 0 -Millisecond 0 -Hour 0 -Year $year -Day $day -Month $month)
    }
}

$students = @()
$students += make-student -firstname "Bob"  -lastname "Sinclair" -score 3 -day 1 -month 3
$students += make-student -firstname "Alice"  -lastname "Cooper" -score 8 -day 14 -month 4
$students += make-student -firstname "Frank"  -lastname "Sinatra" -score 7 -day 12 -month 9
$students += make-student -firstname "Oscar"  -lastname "Wilde" -score 7 -day 22 -month 5
$students

Average score

$total = 0
foreach($student in $students) {
    $total += $student.score
}
$avg  = $total/$students.count
$avg

Version 5 Classes

Check PowerShell Version

get-psversion

Making the Student Class

class Student {
        [string]$firstName=""
        [string]$lastName=""
        [int]$score=3
        [System.DateTime]$birthday
        Student ([string]$firstName,[string]$lastName,[int]$score,[int]$day,[int]$month,[int]$year) {
            $this.firstName = $firstName
            $this.lastName = $lastName
            $this.score = $score
            $this.birthday = (get-date -Minute 0 -Second 0 -Millisecond 0 -Hour 0 -Year $year -Day $day -Month $month)
        }
        Student ([string]$firstName,[string]$lastName,[int]$score,[int]$day,[int]$month) {
            $this.firstName = $firstName
            $this.lastName = $lastName
            $this.score = $score
            $this.birthday = (get-date -Minute 0 -Second 0 -Millisecond 0 -Hour 0 -Year 2003 -Day $day -Month $month)
        }
        [string] GetFullName( ) {
            return ("{0} {1}" -f $this.firstName,$this.lastName)
        }
        [string] GetReportLine( ) {
            return ("{0} {1} - {2}/10" -f $this.firstName,$this.lastName,$this.score)
        }
}

Making Bob

[Student]::new

$bob = [Student]::new("Bob","Sinclair",3,2,2)
$alice =  new-object Student("Alice","Cooper",5,3,4)

Checking Bob

$bob | gm
$bob.GetReportLine()

Dotnet classes

Math fun

[System.Math]::Pi
[System.Math]::Sqrt(9)
([System.Math]::pow(1024,3))/1GB

List (More performant adding) and generics

$class = new-object -type System.Collections.Generic.List[Student]

$class.add
$class.add(3)

$class.add((new-object Student("Alice","Cooper",5,3,4)))
$class.add((new-object Student("Bob","Sinclair",5,3,4)))

foreach ($student in $class) { 
    write-host $student.getReporttLine() 
}

Enum (version 5)

Defining an enumeration

enum GeometricShape {
    Circle = 0
    Triangle
    Square
    Rectangle
}

Using it in a class

class Shape {
    [GeometricShape]$type
    [int]$surfaceArea
    Shape([GeometricShape]$type,[int]$surfaceArea) {
        $this.type = $type
        $this.surfaceArea = $surfaceArea
    }
}

Making a new object

$myshape = new-object Shape("Circle",9)
$myshape | gm
$myshape.type = "try just a random string"
$myshape.type = "circle"

switch($myshape.type) {
    [GeometricShape]::Square {
        write-host "Loving those corners"
    }
    "Circle" {
        write-host "Round, round, round it goes"
    }
    default {
        write-host ("Don't know {0}" -f $myshape.type)
    }
}

$myshape.type = 1
$myshape.type

Getting possible values

[System.Enum]::GetValues([GeometricShape])

Some example of enum values in your system

[System.Enum]::GetValues([System.DayOfWeek])
[System.Enum]::GetValues([System.DateTimeKind])
[System.DateTimeKind]::Utc -eq 1

References System.Math.aspx) System.Collections.Generic.List.aspx)

Inheritance

class Person {
    $first
    $last
    [System.DateTime]$birthday
    Person($first,$last,$birthday) {
        $this.first = $first
        $this.last = $last
        $this.birthday = $birthday
    }
    [void] sayName() {
        write-host ("Hi my name is {0} {1}" -f $this.first,$this.last)
    }
}

$john = [Person]::new("John","Doe",(get-date))
$john.sayName()
class Student : Person {
    $grade
    Student($first,$last,$birthday,$grade) : base($first,$last,$birthday) {
        $this.grade = $grade
    }
}
$eric = [Student]::new("Eric","Forman",(get-date),1)
$eric.sayName()
$eric | gm
$eric.gettype()
class Teacher : Person {
    $salary
    Teacher($first,$last,$birthday,$salary) : base($first,$last,$birthday) {
        $this.salary = $salary
    }
    [void] sayName() {
        write-host ("Hi I'm a teacher and my name is {0} {1}" -f $this.first,$this.last)
    }
}
$bob = [Teacher]::new("Bob","Sinclair",(get-date),2000)
$bob.sayName()
$school = [System.Collections.Generic.List[Person]]::new()
$school.add($eric)
$school.add($bob)
$school.add($john)
$school.add("susan") #error cause you are not a real person

foreach($p in $school) {
    $p.sayName()
}

Contructors

results matching ""

    No results matching ""