当选择失败时,为什么foreach在这里工作?

时间:2014-01-14 12:47:40

标签: json powershell

我已经在$Response变量中存储了RavenDB服务器中的附件列表。

[{"Size":3040,"Key":"attachments/deployments-7928/output-log","Metadata":{"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0D0"},{"Size":2524,"Key":"attachments/deployments-7927/output-log","Metadata":{
"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0CF"},{"Size":530,"Key":"attachments/tasks-7842/output-log","Metadata":{"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0AA"}]

我想获取Key值,以便我可以获取附件。

为什么我不能像这样选择Key值?

$Response | ConvertFrom-Json | Select Key

当我这样做时,所有的键看起来都是空的。

奇怪的是,当我使用Foreach时它会起作用。

$Response | ConvertFrom-Json | Foreach { $_.Key }

我明白这一点:

attachments/deployments-7928/output-log
attachments/deployments-7927/output-log
attachments/tasks-7842/output-log

有什么区别?

为什么不在这里选择工作?

3 个答案:

答案 0 :(得分:1)

如果您首先将结果分配给变量,然后将其传递给Select-Object,则它会起作用。

$response = @'
    [{"Size":3040,"Key":"attachments/deployments-7928/output-log","Metadata":{"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0D0"},{"Size":2524,"Key":"attachments/deployments-7927/output-log","Metadata":{
    "ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0CF"},{"Size":530,"Key":"attachments/tasks-7842/output-log","Metadata":{"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0AA"}]
'@

$ObjectList = $response | ConvertFrom-Json;

$ObjectList | Select-Object -Property Key;

答案 1 :(得分:1)

因为convertfrom-json不返回PSObjects数组,所以它返回一个数组system.object []。该数组没有'Key'成员。

 Write-Output '[{"Size":3040,"Key":"attachments/deployments-7928/output-log","Metadata":{"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0D0"},{"Size":2524,"Key":"attachments/deployments-7927/output-log","Metadata":{
"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0CF"},{"Size":530,"Key":"attachments/tasks-7842/output-log","Metadata":{"ContentType":"text/xml"},"Etag":"02000000-0000-0014-0000-00000000A0AA"}]' `
| convertfrom-json | get-member

输出

   TypeName: System.Object[]
   ...

请参阅,它只有以下成员:

名称

计数
添加
地址
清除
克隆
的CompareTo
包含
CopyTo从
等于
获取
GetEnumerator的
GetHashCode的
对GetLength
GetLongLength
GetLowerBound
的GetType
GetUpperBound
的GetValue
的IndexOf
初始化
插入
删除
RemoveAt移除
设置
的SetValue
的ToString
项目
IsFixedSize
IsReadOnly
IsSynchronized

LongLength
排名
SyncRoot

分配给变量会转换为TypeName:System.Management.Automation.PSCustomObject 这有一个“关键”成员。 Powershell的内置枚举意识正确地扩展了这一点。

答案 2 :(得分:0)

如果要避免中间变量赋值:

{$response | ConvertFrom-Json}.invokereturnasis() | select key
相关问题