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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With