How does PowerShell Pipeline work – Part 2?

PowerShellMicrosoft TechnologiesSoftware & Coding

In part-1 we have seen the PowerShell pipeline functionality using the ValueFromPipeline property. There is another cmdlet property known as ValueFromPipelineByPropertyName, which is also useful to know the PowerShell pipeline functionality.

Like part-1 command, we can get this property name using the same Get-Command but the filter parameter we will use for the property is ValueFromPipelineByPropertyName.

The below example is for the Stop-Service cmdlet.

(Get-Command Stop-Service).ParameterSets.parameters | where{$_.ValueFromPipelineByPropertyName -eq 'True'} | Select Name,ParameterType

Output

Name ParameterType
---- -------------
Name System.String[]

This means you can use Name property to stop the service. So here we will use Get-Service and its Name property to retrieve services and then we can pass output to the Stop-Service command to stop the services

Get-Service "Spooler","W32Time" | Stop-Service -PassThru

Output

Status Name DisplayName
------ ---- -----------
Stopped Spooler Print Spooler
Stopped W32Time Windows Time

-PassThru switch is to get the output in the console.

Let’s take another example for better understanding. The second example is the Stop-Process command.

(Get-Command Stop-Process).ParameterSets.parameters | where{$_.ValueFromPipelineByPropertyName -eq 'True'} | Select Name,ParameterType

Output

Name ParameterType
---- -------------
Id System.Int32[]
Name System.String[]

So in the Stop-Process, we can pass two values by property name. ID and Name. We will use the Get-Process command to retrieve the output with the above two properties and pass it to the Stop-Process using Pipeline.

Get-Process -Name pythonw, notepad | Stop-Process -Verbose

Get-Process -Id 21320,25740 | Stop-Process -Verbose

This is how the PowerShell pipeline works with the two properties. We can write a code to combine two properties and get a better idea of what to pass using the pipeline.

(Get-Command Stop-Process).ParameterSets.parameters `
| where{($_.ValueFromPipelineByPropertyName -eq 'True')
-or ($_.ValueFromPipeline -eq "True")} `
 | Select Name,ParameterType,ValueFromPipeline, ValueFromPipelineByPropertyName

Output

Just check for the property for which value is True and you can pass according to the PowerShell pipeline.

raja
Published on 16-Oct-2020 13:18:30
Advertisements