Powershell - Playing with the -PipelineVariable parameter

To support me, you can subscribe to the channel, share and like the videos, disable your ad blocker or make a donation. Thank you!

Hello,

In PowerShell, the -PipelineVariable parameter stores the current pipeline value as a variable for a cmdlet in the pipeline flows. This allows for some interesting results when using the pipeline. A large number of commands support the -PipelineVariable parameter.

#List cmdlets with the pipelinevariable parameter.
Get-Command -ParameterName pipelinevariable
# Example for creating a tree structure
2021, 2022 |
ForEach-Object -PipelineVariable year -process { $_ } |
Foreach-Object -PipelineVariable month -process {
1..12 | ForEach-Object {(Get-culture).DateTimeFormat.GetMonthName($_)}} |
ForEach-Object -process {
'{0}\{1}' -f $year, $month
#mkdir ( '{0}\{1}' -f $year, $month )
}
# Result
2021January
2021February
...
2022\november
2022\December
# contains the result of "2021, 2022 | ForEach-Object -process { $_ }".
# $month contains the result of "Foreach-Object -process { 1..12 | ForEach-Object {(Get-culture).DateTimeFormat.GetMonthName($_)}}"
# Using another syntax without -pipelinevariable to help clarify the previous behaviour and loop nesting in particular
foreach ($year in 2021, 2022) {
foreach ($month in (1..12 | ForEach-Object {(Get-culture).DateTimeFormat.GetMonthName($_)})) {
'{0}\{1}' -f $year, $month
#mkdir ( '{0}\{1}' -f $year, $month )
}
}
# Another example of listing a user's group membership in AD using -PipelineVariable
Get-ADUser guillaume -PipelineVariable user -Properties memberof |
Select-Object -ExpandProperty memberof |
Select-Object @{ name = 'Name'; expression = { $user.Name }},
@{ name = 'Memberof' ; expression = { $_ -replace 'CN=|,(OR|CN)=.+' }}
# If the cmdlet does not have the -PipelineVariable parameter, it is also possible to use a Where-Object
1, 2, 3, 4 | Where-Object { $true } -PipelineVariable demo | ForEach-Object -Process { $demo }

Related links