Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell : Use a Select-Object expression with a string

Tags:

powershell

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?

like image 887
plunkets Avatar asked Jun 04 '13 14:06

plunkets


People also ask

How do I convert an object to a string in PowerShell?

The Out-String cmdlet converts input objects into strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the Stream parameter to direct Out-String to return one line at a time or create an array of strings.

How do you select an object in PowerShell?

The Select-Object cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array. To select objects from a collection, use the First, Last, Unique, Skip, and Index parameters.

What is the use of $_ in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What does $() mean in PowerShell?

Subexpression operator $( ) For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression. PowerShell Copy.


1 Answers

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.

like image 138
CB. Avatar answered Oct 17 '22 01:10

CB.