Automatically Downloading Pictures via Google Picture Search

by Apr 25, 2014

In a previous tip you learned how you can use Invoke-WebRequest to get image links from Google Image Search. Invoke-WebRequest can do better, though. It can take the image URLs and automatically download the pictures.

Here is how:

$SearchItem = 'PowerShell'
$TargetFolder = 'c:\webpictures'

if ( (Test-Path -Path $TargetFolder) -eq $false) { md $TargetFolder }

explorer.exe $TargetFolder

$url = "https://www.google.com/search?q=$SearchItem&espv=210&es_sm=93&source=lnms&tbm=isch&sa=X&tbm=isch&tbs=isz:lt%2Cislt:2mp"

$browserAgent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36'
$page = Invoke-WebRequest -Uri $url -UserAgent $browserAgent
$page.Links | 
  Where-Object { $_.href -like '*imgres*' } | 
  ForEach-Object { ($_.href -split 'imgurl=')[-1].Split('&')[0]} |
  ForEach-Object {
    $file = Split-Path -Path $_ -Leaf
    $path = Join-Path -Path $TargetFolder -ChildPath $file
    Invoke-WebRequest -Uri $_ -OutFile $path
  } 

This will download all highres images matching the keyword “PowerShell” to your folder specified in $TargetFolder.

Twitter This Tip! ReTweet this Tip!