Advertisement
allywilson

Get APOD archive

Apr 18th, 2020
1,615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Where you want to store the pictures
  2. $DownloadPath = "/home/allywilson/Pictures/wallpapers"
  3.  
  4. # The Astronomy Picture of the Day base URL
  5. $apod = "https://apod.nasa.gov/apod"
  6.  
  7. # Let's get the archive page as it has all the links to the picture pages
  8. $ArchivePixPage = Invoke-WebRequest -Uri "$($apod)/archivepix.html"
  9.  
  10. #Let's filter through all the links on the page and get the ones that begin with "ap" and end with ".html"
  11. $ArchivePixPageLinks = $ArchivePixPage.Links.href | Where-Object {$_ -like "ap*.html"}
  12.  
  13. # While $i does not equal the number of links to ap*.html stay in this loop.
  14. $i = 0
  15. while ($i -lt $ArchivePixPageLinks.Count){
  16.  
  17.     # Let's get the JPG link within the ap*.html page
  18.     #  This line of code is also longer than 120 chars which goes against my aesthetics :-(
  19.     #  But, I don't want to sacrifice readability and invoke my code-golf past.
  20.     $picLinkRef = ((Invoke-WebRequest -uri "$($apod)/$($ArchivePixPageLinks[$i])").Links | Where-Object {$_.href -like "image/*.jpg"}).href
  21.  
  22.     # Wait, what if there's more than 1 *.jpg link? Declaring [0] ruins single strings, so this is a bit of a hack.
  23.     if ($picLinkRef -gt 0){
  24.  
  25.         # For every *.jpg link we find, we loop through it (these are more common than I expected).
  26.         Foreach ($ref in $picLinkRef){
  27.  
  28.             # Let's see if we already have this file, if we do skip it (helpful if you got bored and killed script).
  29.             if (!(Test-Path "$DownloadPath/$(($ref -split '/')[-1])")){
  30.  
  31.                 # Let's download the pic and say where we are in the loop.
  32.                 "Downloading number $($i) of $(($ArchivePixPageLinks).count)...$(($ref -split '/')[-1])"
  33.                 Invoke-WebRequest -Uri "$($apod)/$($ref)" -OutFile "$($DownloadPath)/$(($ref -split '/')[-1])"
  34.  
  35.                 # Please don't remove the below, I don't want to kill APOD web servers.
  36.                 Start-Sleep 2
  37.             }
  38.         }
  39.     }
  40.  
  41.     # Increment $i so we're not stuck in a forever loop.
  42.     $i++
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement