在 PowerShell 中访问对象属性的值 [英] Accessing values of object properties in PowerShell
问题描述
我正在浏览一组对象,我可以很好地显示这些对象.
I'm going through an array of objects and I can display the objects fine.
$obj
在我的 foreach 循环中很好地显示每个对象.我正在尝试访问对象字段及其值.此代码也可以正常工作:
displays each object in my foreach loop fine. I'm trying to access the object fields and their values. This code also works fine:
$obj.psobject.properties
为了只查看每个对象字段的名称,我这样做:
To just see the names of each object's fields, I do this:
$obj.psobject.properties | % {$_.name}
这也很好用.
当我尝试通过这样做访问这些字段的值时:
When I try to access the values of those field by doing this:
$obj.psobject.properties | % {$obj.$_.name}
没有返回或显示任何内容.
nothing is returned or displayed.
这样做是为了诊断目的,看看我是否可以访问字段的值.主要的困境是我无法访问特定字段的值.IE.
This is done for diagnostic purposes to see whether I can access the values of the fields. The main dilemma is that I cannot access a specific field's value. I.e.
$obj."some field"
即使我已经确认某个字段"有值也不会返回值.
does not return a value even though I have confirmed that "some field" has a value.
这让我很困惑.有谁知道我做错了什么?
This has baffled me. Does anyone know what I'm doing wrong?
推荐答案
一旦你遍历了 foreach 中的属性,它们就会通过 $_
(当前对象符号)变得可用.就像您使用 $_.Name
打印属性名称一样,使用 $_.Value
将打印它们的值:
Once you iterate over the properties inside the foreach, they become available via $_
(current object symbol). Just like you printed the names of the properties with $_.Name
, using $_.Value
will print their values:
$obj.psobject.properties | % {$_.Value}
这篇关于在 PowerShell 中访问对象属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!