8

For some scripts, i need to have an output composed of calculated properties.

For example, for a list of ip addresses in ip.txt, i want to know if they respond to ping. So i try the following command:

Get-Content .\ip.txt | Select-Object $_,@{Name="ping?";Expression={Test-Connection $_ -Quiet -Count 1}}

But i get an error, regardless of what i do in the scriptblock expression.

The error (in french, sorry):

Select-Object : Paramètre Null. Le type attendu doit être l'un des suivants : {System.String, System.Management.Automation.ScriptBlock}. Au niveau de ligne : 1 Caractère : 37 + Get-Content .\ip.txt | Select-Object <<<< $_,@{Name="ping?";Expression={Test-Connection $_ -Quiet -Count 1}} + CategoryInfo : InvalidArgument: (:) [Select-Object], NotSupportedException + FullyQualifiedErrorId : DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand

I used the "calculated properties" in some scripts before, but with directories objects. Why it doesnt work with strings?

jpaugh
  • 6,634
  • 4
  • 38
  • 90
plunkets
  • 510
  • 1
  • 6
  • 13

1 Answers1

17

try this instead, you need to create calculated properties for each value:

Get-Content .\ip.txt | Select-Object  @{n="Server IP";e={$_}},@{n="ping?";e={[bool](Test-Connection $_ -Quiet -Count 1)}}

The problem in your code is the $_ not the calculated property. Select-object accept and array of properties, if in the array you pass $_ isn't evaluated as a property. If you do just select-object $_ (as select-object -prop $null ) piped items are the output.

CB.
  • 58,865
  • 9
  • 159
  • 159
  • Thanks! I tried "select-object $_" with success too, so i believed that the problem was the calculated property for a string object. – plunkets Jun 04 '13 at 16:39
  • So the gotcha here is that `{n="label"; e=$_ }` will fail but putting `$_` inside braces succeeds: `{n="label"; e={$_ }}` ? Similarly for other expressions, `e=expression` will often fail, it has to be `e={expression}` – Chris F Carroll Aug 19 '22 at 10:30
  • The docs example on the magical `@{n=;e=}` syntax for projections show but don't tell : https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/select-object?view=powershell-7.2#example-11-create-calculated-properties-for-each-inputobject – Chris F Carroll Aug 19 '22 at 10:36