从REST API调用,我尝试使用以下代码将响应存储在csv中
$response = Invoke-RestMethod 'http://api.ipstack.com/54.251.51.24?access_key=mykey&security=1&hostname=1' -Method 'GET' -Headers $headers |
Select-Object ip,hostname -ExpandProperty time_zone |
Select-Object ip,hostname,@{N='time_zone_code';E={$_.code}} -ExpandProperty location |
Select-Object ip,hostname,time_zone_code,@{N='location_geoname_id';E={$_.geoname_id}} -ExpandProperty languages |
Select-Object ip,hostname,location_geoname_id,time_zone_code,@{N='languages_native';E={$_.native}} |
Export-Csv C:\Users\Lenovo\Desktop\Danial\response.csv -NoTypeInformation -Append
它给我下面的错误
Select-Object : Property "location" cannot be found.
At line:3 char:9
+ Select-Object ip,hostname,@{N='time_zone_code';E={$_.code}} - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (@{id=Australia/...e=1.132.104.84}:PSObject)
[Select-Object], PSArgumentException
+ FullyQualifiedErrorId :
ExpandPropertyNotFound,Microsoft.PowerShell.Commands.SelectObjectCommand
我尝试了很多东西,但不知道如何在Select-Object中扩展多个属性。
{
"ip": "54.251.51.24",
"hostname": "54.251.51.24",
"type": "ipv4",
"continent_code": "OC",
"continent_name": "Oceania",
"country_code": "AU",
"country_name": "Australia",
"region_code": "QLD",
"region_name": "Queensland",
"city": "Brisbane",
"zip": "4000",
"latitude": -27.467580795288086,
"longitude": 153.02789306640625,
"location": {
"geoname_id": 2174003,
"capital": "Canberra",
"languages": [
{
"code": "en",
"name": "English",
"native": "English"
}
],
"country_flag": "https://assets.ipstack.com/flags/au.svg",
"country_flag_emoji": "🇦🇺",
"country_flag_emoji_unicode": "U+1F1E6 U+1F1FA",
"calling_code": "61",
"is_eu": false
},
"time_zone": {
"id": "Australia/Brisbane",
"current_time": "2023-03-07T18:54:34+10:00",
"gmt_offset": 36000,
"code": "AEST",
"is_daylight_saving": false
}
}
我想将csv中location和time_zone的所有列存储为可读,而不是System.Object
3条答案
按热度按时间o8x7eapl1#
简单地从数据行创建新对象并导出这些对象可能比使用
Select-Object
更容易:1.设置一些测试数据
1.将数据格式化为CSV友好的格式
1.转换格式化的数据(如果要保存到磁盘,请使用
Export-Csv
):ep6jt1vc2#
访问
location
时出现错误,因为您已经在此处删除了此属性:Select-Object ip,hostname -ExpandProperty time_zone |
将您将要使用的属性添加到所有前面的
select-object
中w8rqjzmb3#
使用以下代码解决了我的问题