Powershell:使用带字符串的Select-Object表达式

plu*_*ets 6 powershell

对于某些脚本,我需要有一个由计算属性组成的输出.

例如,对于ip.txt中的ip地址列表,我想知道它们是否响应ping.所以我尝试以下命令:

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

但是我得到一个错误,不管我在scriptblock表达式中做了什么.

错误(法语,抱歉):

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

我以前在一些脚本中使用了"计算属性",但是使用了目录对象.为什么它不能用于字符串?

CB.*_*CB. 13

试试这个,你需要为每个值创建计算属性:

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

代码中的问题$_不是计算属性. Select-object如果在传递的数组$_中未接受属性,则接受和属性数组.如果你只是select-object $_(作为select-object -prop $ null)管道项是输出.