Chapters/scripting-at-scale/pipelinesamples.ps1


#demonstrate pipeline performance differences
return "This is a demo script file."

#region pipeline vs parameter

$names = get-service | select -expand name

#57ms
measure-command {
 $names | get-service
}

#40ms
measure-command {
 get-service $names
}

$big = $names+$names+$names+$names+$names
#253ms
measure-command {
 $big | get-service
}

#169ms
measure-command {
 get-service $big
}

#endregion

#region breakup a command

#861ms
Measure-Command {
$data = dir $env:temp -file -Recurse | group extension | 
Sort Count | Select Count,Name,@{Name="Size";Expression = { 
($_.group | Measure-object -Property length -sum).sum
}}
}

#779
Measure-Command {
$files = dir $env:temp -file -Recurse
$grouped = $files  | group extension 
$sorted = $grouped| Sort Count
$data = $sorted | Select Count,Name,@{Name="Size";Expression = { 
($_.group | Measure-object -Property length -sum).sum
}}
}

#endregion

#region ForEach vs Foreach-Object

$n = 1..10000

#51.7ms
Measure-command {
 $a = 0
 foreach ($i in $n) {
   $a+=$i
 }
}

#227ms
Measure-command {
 
 $n | foreach-object -Begin { $a = 0 } -process {
   $a+=$_
 }

}

#endregion