gpt4 book ai didi

powershell - 无法在PowerShell中来自JSON的关联数组上调用getEnumerator()

转载 作者:行者123 更新时间:2023-12-03 01:28:03 24 4
gpt4 key购买 nike

   Try {
#Connect to PNP Online
Connect-PnPOnline -Url $siteUrl -UseWebLogin
$json = Get-PnPFile -Url $FolderRelativeURL -AsString
Write-host $json.files
$object = $json | ConvertFrom-Json
$object.items | ForEach-Object {
Write-host $_.folder
$object.files.GetEnumerator() | ForEach-Object {"$($_.Key) - $($_.Value)"}

#$item = Get-PnPFile -Url "$($FolderRelativeURLGeneral) $($_.folder)" -AsString
}

}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

我试图遍历以下json的files键内的变量:
{
"files":{
"item":"item.html",
"header":"header.html",
"content":"content.html",
},
"items":[
{
"folder":"Advert",
"file":"ad2.json"
},
{
"folder":"YouTube",
"file":"ad3.json"
},
]
}

但是,GetEnumerator()方法不适用于该对象的属性文件。有办法使它起作用吗?奇怪的是,它适用于object.items。

运行脚本时出现以下错误:
Error: Method invocation failed because [System.Management.Automation.PSCustomObject] does not contain a method named 'GetEnumerator'.

最佳答案

如错误消息所暗示, ConvertFrom-Json 默认情况下输出[pscustomobject]实例( System.Management.Automation.PSCustomObject )-并且该类型没有枚举器。[1]

在PowerShell [Core] 6+中,您可以使用-AsHashtable开关,该开关返回确实具有[hashtable]方法的.GetEnumerator()实例。

在Windows PowerShell中,必须通过(隐藏的).psobject.Properties集合以不同方式枚举属性(在PowerShell [Core]中也可以使用):

$fromJson = @'
{
"files":{
"item":"item.html",
"header":"header.html",
"content":"content.html",
},
"items":[
{
"folder":"Advert",
"file":"ad2.json"
},
{
"folder":"YouTube",
"file":"ad3.json"
},
]
}
'@ | ConvertFrom-Json

$fromJson.Files.psobject.Properties | foreach {
"$($_.Name) - $($_.Value)"
}

注意需要使用 .Name而不是 .Key;但是,如果要处理哈希表,请注意 .Name也可以使用。

以上 yield :

item - item.html
header - header.html
content - content.html

它适用于 .Items属性,因为它包含一个数组( [object[]),并且数组确实具有 .GetEnumerator()方法。

关于powershell - 无法在PowerShell中来自JSON的关联数组上调用getEnumerator(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60606037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com