PowerShell中从已填充数组提取数据的技术咨询
$jsonDataArray Alright, let's break down how to pull the data you need from that $jsonDataArray—the @{...} output you're seeing just means PowerShell is showing you the string representation of the objects in the array, not that the data is unreadable. Here's what you can do:
First, Understand the Object Structure
Before extracting anything, you need to know what properties are available in each object. Run this command to inspect the first item in your array (replace [0] with another index if you want to check a different entry):
# View all properties of the first object, including nested ones $jsonDataArray[0] | Format-List * -Force
Or to get a clean list of property names:
$jsonDataArray[0] | Get-Member -MemberType NoteProperty
This will show you exactly what fields you can access (like forecast, location, temp, etc., depending on the Weather Channel API's response structure).
Extract Data with Direct Property Access
Once you know the property names, you can access them directly in your ForEach-Object loop. For example, if the API returns a location.city field and daily forecast temps, you'd do something like:
$jsonDataArray | ForEach-Object { Write-Host "City: $($_.forecast.location.city)" Write-Host "Today's High: $($_.forecast.forecastday[0].high.temp)°F" Write-Host "Tomorrow's Low: $($_.forecast.forecastday[1].low.temp)°F`n" }
Note the use of $() inside the string—this tells PowerShell to evaluate the nested property expression instead of treating it as literal text.
Extract Data into a Structured Output (Like a Table)
If you want to export or view the data in a clean table, use Select-Object. You can even create calculated properties to rename fields for clarity:
$jsonDataArray | Select-Object -Property ` @{Name='City'; Expression={$_.forecast.location.city}}, @{Name='TodayHigh'; Expression={$_.forecast.forecastday[0].high.temp}}, @{Name='TomorrowLow'; Expression={$_.forecast.forecastday[1].low.temp}}
This will output a neat table with your desired fields.
Handle Nested Arrays (e.g., Multiple Forecast Days)
If you need to iterate through each day's forecast individually (instead of just grabbing day 0 and 1), nest another loop:
$jsonDataArray | ForEach-Object { $city = $_.forecast.location.city foreach ($day in $_.forecast.forecastday) { [PSCustomObject]@{ City = $city Date = $day.date HighTemperature = $day.high.temp LowTemperature = $day.low.temp Condition = $day.conditions } } }
This will create a flat list of objects, one for each day of the forecast per IP address.
Quick Debug Tip
If you're unsure about a property path, you can test it on a single object first:
# Test if a property exists and returns data $jsonDataArray[0].forecast.location.city
If this returns a value, you know the path is correct.
内容的提问来源于stack exchange,提问作者W T

