Powershell - API interaction

Normally I would do this with cURL and jq

Download random image or a pet from an API providing a url path to an image file

  • First part is get the current time specifically the second.
  • Divide the second by 2 and determine if it is an odd or even number, I'm doing this with simple math of (X / 2 - Truncate(X / 2)) * 10 = 5 so say for 5 you get 2.5 - 2 = .5, then .5 * 10 to shift decimal place and then compare to 5
  • Use Invoke-WebRequest to make API call ( cURL normally goes here ) Invoke-WebRequest "API URL"
  • Read the json response and parse out the download url ConvertFrom-Json | Select-Object ... details of response here
  • Read the filename from the url response extracted $filename = $url.Substring($url.LastIndexOf("/") + 1)
  • Save the url to the temp directory as the filename extracted Invoke-WebRequest $url -OutFile $imagePath
  • Open the file with default image extension handler Invoke-Item $imagePath
$second = (Get-Date).Second
$url = ""
if (((($second /2) - [math]::Truncate($second / 2)) * 10) -eq 5) {
	$url = (Invoke-WebRequest https://api.thecatapi.com/v1/images/search | ConvertFrom-Json | Select-Object).url
}
else {
	$url = (Invoke-WebRequest "https://dog.ceo/api/breeds/image/random" | ConvertFrom-Json | Select-Object -Property message).message
}

$filename = $url.Substring($url.LastIndexOf("/") + 1)
$imagePath = "$env:temp\$filename"
Invoke-WebRequest $url -OutFile $imagePath
Invoke-Item $imagePath