在此对象上找不到属性“X”。验证该属性是否存在

问题描述 投票:0回答:1

我在脚本中有以下函数片段,该函数片段抛出错误:在此对象上找不到属性“timeoffs”。我已验证该属性存在。

function GetoffTime($startDate, $endDate, $teamUsers) {
    foreach ($user in $teamUsers){
      $body = @{
      "users" = @($user)
      } | ConvertTo-Json -compress
      
      $response = Invoke-WebRequest -Uri $URL -Method POST -Headers $headers -ContentType "application/json" -Body $body
      if ($response.StatusCode -eq "200") {
        $data = ConvertFrom-Json $response
        
        foreach($element in $data){
            #It would throw the property not found error at if statement below
            if($element.items.timeoffs.start.date){
            $timeoff += @{
              username = $element.items.username
              date = $element.items.timeoffs.start.date | Sort-Object
            }
    }
  }
  catch {
      Log-msg
  }
  return $timeoff
}

如果我在PS和convertfrom-json中手动执行 $response = Invoke-WebRequest -Uri $URL -Method POST -Headers $headers -ContentType "application/json" -Body $body (就像在函数中一样),则“timeoffs”属性确实存在,如下所示。但是当在函数中执行时,我无法访问该属性。 enter image description here

我读到我应该像 [Object]$data 这样添加前缀,但没有运气。我可能弄错了一些东西,希望得到建议。

powershell
1个回答
0
投票

我认为这是你的错误,因为我在以下代码片段中没有错误:

$data = ConvertFrom-Json '[{"items": { "username": "whatever", "timeoffs": { "start": { "date": "2024-09-21" } } }} ]'
echo $data.items.timeoffs.start.date

我读到我应该像

[Object]$data
这样的前缀,但没有运气。

ConvertFrom-Json
的返回类型是类似
Dictionary
的类型。 文件说:

输出

PS自定义对象

有序哈希表

转换为

System.Object
不允许您访问 JSON 属性,因为
System.Object
不知道此类属性。

© www.soinside.com 2019 - 2024. All rights reserved.