In this video I demonstrate how you should use a pipeline based function.
*powershell
*learn powershell
*automation
*learn automation
*windows powershell
*automatic deployment
Code:
function get-mrbexample {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipeline)] $item
)
begin {
#for instance you setup a DB connection here
#you can also init value and use that in the process block for each item.
$myval = 1
Write-output "This runs once for the whole array"
}
process {
#here you can use the DB connection object
Write-Output "This runs for each item in the array : $($item.fullname) : $myval"
}
end {
#here you disconnect again from the database and cleanup if needed
Write-Output "This also runs once for the whole array"
}
}
#array with some examples for the loop
$all = Get-ChildItem c:\Windows
#correct way of pipeline usage
$all | get-mrbexample
#dont use begin process end in function when you call the like this.
#not recommended
for($i=0; $i -lt $all.count; $i++){
#2 examples they do the same, since its singlebased object that is passed to the function
$all[$i] | get-mrbexample
#get-mrbexample -item $All[$i]
}
#not recommended
$all.ForEach({$_ | get-mrbexample})
#not recommended
$all | ForEach-Object {$_ | get-mrbexample}
#not recommended
foreach($t in $all){
#2 examples they do the same, since its singlebased object that is passed to the function
$t | get-mrbexample
#get-mrbexample -item $t
}
Watch video PowerShell - Pipeline based functions online, duration hours minute second in high quality that is uploaded to the channel Mr Automation 05 June 2022. Share the link to the video on social media so that your subscribers and friends will also watch this video. This video clip has been viewed 296 times and liked it 9 visitors.