Using Property Names in a PowerShell Pipeline $ _ variable

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  #why no intellisense here? 
 }


foreach ($item in Get-Service) 
 {
    Write-Host $item.Name 
 }
+4
source share
3 answers

: $_, , script . script *-Object ( ). / . Write-Host , .

: , (GetServices). PowerShell v3 intellisense (OutputType). - / , OutputType, intellisense . , - intellisense :

function Get-ServiceEx {
[OutputType('System.ServiceProcess.ServiceController')]
param ()
    'This is not really a service!'
}

(Get-ServiceEx).<list of properties of ServiceController object>

.

+4

Intellisense , $_ . intellisense:

Get-Service | Foreach-Object {$_.Name} # Intellisense works
Get-Service | Where-Object {$_.Name}   # Intellisense works
Get-Service | Write-Host {$_.Name}     # Intellisense works

, : , intellisense $_, .

, , $_ (, switch,%,?), .

+2

$_ - . , $item foreach ($item in $array).

Get-Service | Where {$_.name -Match "host" } 

Get-Service | Write-Host $_.name

PowerShell. . . , :

Get-ChildItem *.txt | Remove-Item

, , . , .

Where-Object Foreach-Object. , . ( ), , $_. $_ , ( Write-Host).

Intellisense foreach ($item in Get-Service). .

0

Source: https://habr.com/ru/post/1538467/


All Articles