filmov
tv
PowerShell - Pipeline based functions
Показать описание
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
}
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
#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
}
*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
}
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
#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
}