简体   繁体   English

如何为具有多个来自CSV变量的API调用设计“ Invoke-WebRequest”? (电源外壳)

[英]How to design an “Invoke-WebRequest” for multiple API calls with more than one variable from CSV? (Powershell)

I am trying to call Dark Sky API for weather forecast data for each location in a CSV file with hundreds lines and write them to a text file. 我试图调用Dark Sky API以获取具有数百行的CSV文件中每个位置的天气预报数据,并将其写入文本文件。 Here's an example of the first 5 lines of the CSV... 这是CSV的前5行的示例...

ip              city        region_code zip     latitude  longitude
75.161.17.209   Albuquerque NM          87114   35.1868  -106.6652
68.55.28.227    Plymouth    MI          48170   42.3688  -83.4799
72.95.198.227   Homestead   PA          15120   40.3926  -79.9052
68.180.94.219   Normal      IL          61761   40.5124  -88.9883
75.132.165.245  Belleville  IL          62226   38.5352  -90.0006

The uri is formatted like this... uri的格式如下:

https://api.darksky.net/forecast/[APIKey]/$latitude ,$longitude ,$ForcastTime ?exclude=currently,minutely,hourly,flags&units=us

There are 3 variables in this uri. 此uri中有3个变量。 $latitude, $longitude, and $ForecastTime. $ latitude,$ longitude和$ ForecastTime。 $ForecastTime is easy, because it is the same for all requests, so I have that defined already as... $ ForecastTime很容易,因为所有请求都相同,因此我已经将其定义为...

$ForecastTime = Get-Date -Date $(Get-Date).AddDays(1) -Format yyyy-MM-ddTHH:mm:ss

...in order to give me Tomorrow's forecast info. ...为了给我明天的预报信息。 This is the format Dark Sky calls for and works just fine. 这是Dark Sky要求的格式,并且效果很好。

I'm having trouble defining $latitude & $longitude as variables and formatting the Invoke-WebRequest so I can pull the weather data for the entire string of locations. 我在将$ latitude和$ longitude定义为变量并格式化Invoke-WebRequest时遇到麻烦,因此我无法提取整个位置字符串的天气数据。

Any help would be appreciated. 任何帮助,将不胜感激。

Here is some sample code with Invoke-RestMethod but you can also work with Invoke-WebRequest . 这是Invoke-RestMethod一些示例代码,但是您也可以使用Invoke-WebRequest I like using Invoke-RestMethod for interacting with APIs.. Try and let me know if it works or not. 我喜欢使用Invoke-RestMethod与API进行交互。请尝试让我知道它是否有效。

$ForecastTime = Get-Date -Date $(Get-Date).AddDays(1) -Format yyyy-MM-ddTHH:mm:ss;
Import-CSV './input.csv' | ForEach-Object {
     $result = Invoke-RestMethod -Uri "https://api.darksky.net/forecast/$apiKey/$_.latitude,$_.longitude,$ForcastTime?exclude=currently,minutely,hourly,flags&units=us"
}

PS: If a CSV column name has spaces in it then you can read the column as $_.'Region Code' PS:如果CSV列名称中包含空格,则可以将该列读为$_.'Region Code'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM