As a C # developer, I still learn the basics of PowerShell and am often confused. Why $ _. give me an intellisense list of vaild property names in the first example, but not the second?
Get-Service | Where {$_.name -Match "host" }
Get-Service | Write-Host $_.name
What is the main difference between these two examples?
When I run the second, it gives this error on each iteration of Get-Service:
Write-Host : 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.
At line:3 char:15
+ Get-Service | Write-Host $_.name
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (wuauserv:PSObject) [Write-Host], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.WriteHostCommand
My colleague and I first used the foreach loop to iterate through the Get-commandlet, and we were stuck getting the property names. We tried to simplify it until we move on to the basic principles above.
It just turned out that sometimes this is a typo on the command line, a failure below the first one, because the command line should have Get-Service instead of Get-Services.
foreach ($item in Get-Services)
{
Write-Host $item.xxx
}
foreach ($item in Get-Service)
{
Write-Host $item.Name
}
source
share