header image

PowerShell Basics: 4 Pipeline

Posted by: | June 1, 2011 | No Comment |

The pipeline give PowerShell a massive amount of power. The ability to pipe objects between cmdlets enables us to perform processing very simply that would take a lot of code in another scripting language.

Sometimes the pipeline doesn’t seem to work.  For example – this works

Get-Service s* | Stop-Service –WhatIf

but this doesn’t

Get-ChildItem -Path c:\test -Filter proc?.txt | Copy-Item c:\test\xyx.txt

We get an error that says

Copy-Item : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

This is due to the properties that Get-ChildItem produces not matching what Copy-Item is expecting. If you check the help – Inputs section – for Copy-Item you will see that it can accept a string that contains the path to the item to copy.  If we look at the entry for the    –Path parameter on Copy-Item

Path <string[]>

Specifies the path to the items to copy.
Required?                   true
Position?                   1
Default Value               none
Accept Pipeline Input?      true (ByValue, ByPropertyName)
Accept Wildcard Characters? false

But Get-ChildItem doesn’t output a property called path so Copy-Item doesn’t know what to copy.

We have to  use foreach-object like this

Get-ChildItem -Path c:\test -Filter proc?.txt |
foreach {Copy-Item $_.Fullname c:\test\xyx.txt -WhatIf }

So the pipeline isn’t failing it is the fact that the output properties and input parameters don’t match.

This should hopefully clear the confusion as to why sometimes we can pipe and sometimes we have to use foreach

under: PowerShell Basics