Created
May 15, 2016 23:38
-
-
Save NicholasLeader/e5eb35f7e2d3a28076d5b17c1b3e2bc3 to your computer and use it in GitHub Desktop.
PowerShell API JSON example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
Nicholas Leader | |
05/15/2016 | |
Example of using the api.ipify.org API in the JSON format | |
Optional text version of the API would be more straight forward, | |
this demonstrating some manual parsing of the JSON format. | |
JSON format can also be converted to a PowerSHell object via 'convertFrom-Json' cmdlet: | |
(Invoke-WebRequest -URI https://api.ipify.org?format=json) | ConvertFrom-Json | Select-Object | |
#> | |
# get today's date in a nice string format, and store it in a variable | |
$date= Get-Date -Format 'yyyyMMdd.hh.mm' | |
# path that we're going to write the resultant file to, including a date stamp | |
$path_of_export = "C:\test\$date.testing.csv" | |
# 'invoke-webrequest' is similar to 'wget' in BASH, infact it has the alias of 'wget' in PowerShell | |
# splitting on '"' in the 'content' property of the returned object and storing the resultant array in the '$IPlookUP' variable | |
$IPlookUP = (Invoke-WebRequest -URI https://api.ipify.org?format=json).content -split '"' | |
# grabbing the third element in the array which contains the IP | |
$IPlookUP[3] | | |
# performing a calculated property with 'select-object' to associate 'IP' as the property name with the value of the IP | |
Select-Object @{name='IP';expression={$_}} | | |
# writing the selected object to a CSV export | |
export-csv -NoTypeInformation -Path $path_of_export | |
# Letting the using know the file name created | |
write-host "" | |
write-host "File written to " -NoNewline ; write-host -ForegroundColor Green $path_of_export | |
<# | |
example of checking contents of newly created file | |
import-csv -path $path_of_export | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment