PowerShell - Playing with the -PipelineVariable parameter
2 min read · Updated 22 December 2022
Hello,
In PowerShell, the -PipelineVariable parameter stores the current pipeline value as a variable for a cmdlet in a pipeline.
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 structure2021, 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 ) }# Result2021January2021February...2022\november2022\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 particularforeach ($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 -PipelineVariableGet-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-Object1, 2, 3, 4 | Where-Object { $true } -PipelineVariable demo | ForEach-Object -Process { $demo }Related links
- PowerShell
PowerShell - Simply send objects to different variables
PowerShell - Tip - Simply send objects to different variables
1 min read
- PowerShell
PowerShell - Testing network connectivity and port accessibility
Testing network connectivity and port accessibility with PowerShell
2 min read
- PowerShell
PowerShell - Display network connections (equivalent to netstat)
Display network connections (listening ports, active connections...)
2 min read
- PowerShell
PowerShell - Testing name resolution (equivalent to nslookup)
PowerShell commands to test name resolution (equivalent to nslookup)
2 min read
- PowerShell
PowerShell - View and manage DNS configuration of network interfaces
PowerShell commands to display and manage DNS configuration of network interfaces
4 min read
- PowerShell
PowerShell - Managing IP configuration of network interfaces
PowerShell commands to view and modify the IP configuration of network interfaces
4 min read