The Pipeline
Getting started
Making some 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
Select the name and grade
$students | select firstname, score
Sort By Property
$students | Sort-Object -property LastName
$students | Sort-Object -property Birthday
$students | Sort-Object -property Score
$students | Sort-Object -property Score -Descending
Filtering students
$students | where-object { $_.score -lt 5}
Measuring
$students | measure-object
$students | measure-object -Average -Property Score
$measured = $students | measure-object -Minimum -Property Score
$measured.minimum
$students | measure-object -minimum -Property Birthday | select minimum
For each object, pipeline style
$students | foreach-object { write-host ("Student : {0,-15} `t Score {1}/5" -f $_.Firstname,($_.score/2)) }
Function made for pipeline
function Evaluate-Student {
param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
$student
)
begin {
write-host "Teacher autobot evaluation"
write-host "##########################"
}
process {
if($student.score -gt 7) {
write-host ("Keep up the good work {0}" -f $student.FirstName)
$student | Add-Member -Name Evaluation -Value "Passed" -Type NoteProperty -Force
} elseif($student.score -gt 5) {
write-host ("It's okay but next year, try to put some more effort in it {0}" -f $student.FirstName)
$student | Add-Member -Name Evaluation -Value "Passed with homework" -Type NoteProperty -Force
} else {
write-host ("This result is miserable {0}" -f $student.FirstName)
$student | Add-Member -Name Evaluation -Value "Failed" -Type NoteProperty -Force
}
}
end {
write-host "##########################"
write-host "Teacher autobot end"
}
}
$students | Evaluate-Student
Evaluate-student -student $students[0]
Show output as table
$students | format-table
Show output as list
$students | format-list
Kill all notepad!
Get-Process -name notepad | Stop-Process