Advertisement
Guest User

Get Cats

a guest
Nov 12th, 2018
720
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #Prompt for how many cat pictures we're going to retrieve
  2. $cats = Read-Host -Prompt 'Input how many cats you want'
  3.  
  4. #start the loop
  5. For ($i=1; $i -le $cats; $i++)
  6. {
  7.     #set the filename. This will be useful
  8.     $Filename = "Cat $i"
  9.  
  10.     #store the file with a temporary name
  11.     Invoke-WebRequest "https://api.thecatapi.com/api/images/get?format=src&results_per_page=1" -OutFile "$Filename"
  12.    
  13.     #open the file as binary so we can check the header to determine the file type
  14.     $a = [System.IO.File]::ReadAllBytes("$Filename");
  15.  
  16.     #read the relevant bits for GIF
  17.     $header = "{0:X2}" -f $a[0]
  18.     $header += "{0:X2}" -f $a[1]
  19.     $header += "{0:X2}" -f $a[2]
  20.  
  21.     #check if the header says it's a GIF
  22.     If ($header -eq "474946") {
  23.         #If it is, tell the user the filename and move the temporary file to the correct name
  24.         Write-Host "$Filename.gif"
  25.         Move-Item -Path $Filename -Destination "$Filename.gif"
  26.     }
  27.  
  28.     #read the relevant bits for JPG (JFIF)
  29.     $header = "{0:X2}" -f $a[6]
  30.     $header += "{0:X2}" -f $a[7]
  31.     $header += "{0:X2}" -f $a[8]
  32.     $header += "{0:X2}" -f $a[9]
  33.  
  34.     #check if the header says "JFIF"
  35.     If ($header -eq "4A464946") {
  36.         #If it is, tell the user the filename and move the temporary file to the correct name
  37.         Write-Host "$Filename.jpg"
  38.         Move-Item -Path $Filename -Destination "$Filename.jpg"
  39.      }
  40.  
  41.      #read the relevant bits for PNG
  42.      $header = "{0:X2}" -f $a[1]
  43.      $header += "{0:X2}" -f $a[2]
  44.      $header += "{0:X2}" -f $a[3]
  45.  
  46.      #check if the header says "PNG"
  47.      If ($header -eq "504E47") {
  48.         #If it is, tell the user the filename and move the temporary file to the correct name
  49.         Write-Host "$Filename.png"
  50.         Move-Item -Path $Filename -Destination "$Filename.png"
  51.      }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement