代码之家  ›  专栏  ›  技术社区  ›  glenatron

Powershell是否有“eval”等价物?有没有更好的方法来查看属性和值的列表?

  •  6
  • glenatron  · 技术社区  · 16 年前

    我正在做一点Powershell脚本(第一次)来查看Sharepoint站点中的一些内容,我希望能够遍历对象的属性列表,并以“property name=value”的格式输出它们的值。

    $myObject | get-member -membertype property
    

    它将以非常清晰易读的方式返回所有属性的列表。但我需要的是找到这些属性的值。

    在某些脚本语言中,我可以有一种eval(“$myObject.$propertyName”)调用—我从get成员输出中提取了$propertyName—并让它将字符串作为代码进行计算,对于我需要的那种快速而肮脏的解决方案来说,这是很好的。

    3 回复  |  直到 16 年前
        1
  •  8
  •   Steven Murawski    16 年前

    要获取对象属性的值,可以使用多种方法。

    首先,可以使用Select Object和-Property参数来指定要返回的属性值。其显示方式将取决于指定的属性数和对象类型。如果需要所有属性,可以使用通配符(*)获取所有属性。

    示例-

    $myobject | Select-Object -Property name, length
    $myobject | Select-Object -Property *
    

    $myobject | Format-List -Property *
    $myobject | Format-Table -Property name, length
    

    最后,要执行“eval”样式的输出,您可以简单地键入

    $myobject."$propertyname" 
    

        2
  •  1
  •   stej    16 年前

    对你来说最好的选择是 Format-Custom

    get-date | Format-Custom -Depth 1 -Property * 
    get-childitem . | select-object -first 1 | Format-Custom -Depth 1 -Property *
    

    可能太冗长了,但很有用;)


    Get-Member

    $obj = get-date
    $obj | 
       gm -MemberType *property | 
       % { write-host ('{0,-12} = {1}' -f $_.Name, $obj.($_.Name)) }
    
        3
  •  1
  •   Keith Hill    16 年前

    为此,我建议使用格式列表-force,例如:

    Get-Process | Format-List * -Force
    

    -强制是可选的,但有时PowerShell会隐藏我真正想看到的属性。