Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all articles
Browse latest Browse all 15028

ForEach-Object bug?

$
0
0

According to Get-Help ForEach-Object, ForEach-Object receives an input object which can be either piped or passed using the -InputObject parameter.

However, this doesn't appear to be the case. Here's a quick example:

Get-Service | ForEach-Object {Write-Host $_.Name}

This will correctly output the name of each of the services on the computer, as expected.

However, the variation below will simply output a single blank line.

$services = Get-Service

ForEach-Object -InputObject $services {Write-Host $_.Name}

Moreover, doing:

$services = Get-Service

$services | ForEach-Object {Write-Host $_.Name}

Works absolutely fine.

Closer inspection shows that in the example that doesn't work, $_ -eq $services, meaning that ForEach-Object is not actually getting each of the objects inside the object collection.

Running the following code will output the name of the first service in the collection twice, showing that $_ -eq $services.

$services = Get-Service

#Check what the name of $services[0] is

Write-Host $services[0].Name

ForEach-Object -InputObject $services {Write-Host $_[0].Name}

Can anyone explain this?



Viewing all articles
Browse latest Browse all 15028

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>