10

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?

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! I tried "select-object $_" with success too, so i believed that the problem was the calculated property for a string object.
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}
The docs example on the magical @{n=;e=} syntax for projections show but don't tell : learn.microsoft.com/en-us/powershell/module/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.