【问题标题】:Powershell : Use a Select-Object expression with a stringPowershell:使用带有字符串的 Select-Object 表达式
【发布时间】:2013-06-04 14:40:12
【问题描述】:

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

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

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

但是无论我在脚本块表达式中做什么,我都会遇到错误。

错误(法语,抱歉):

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

我之前在一些脚本中使用了“计算属性”,但使用了目录对象。为什么它不适用于字符串?

【问题讨论】:

    标签: powershell


    【解决方案1】:

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

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

    代码中的问题是 $_ 不是计算属性。 Select-object 接受和属性数组,如果在您传递的数组中 $_ 不被评估为属性。 如果您只执行 select-object $_ (作为 select-object -prop $null )管道项目是输出。

    【讨论】:

    • 谢谢!我也成功尝试了“select-object $_”,所以我认为问题出在字符串对象的计算属性上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多