Skip to content

Download all PDFs from a web page via PowerShell

G6th December 2016

CNo Comments

TPowerShell

Use PowerShell to download every PDF from a web page and save them to a nominated folder.

I recently needed to download a lot of PDF documents from a web page and thought that I’d get PowerShell to do the hard work for me.

The following PowerShell code will open a folder dialogue box and then download every PDF within the web page specified in the code to the designated folder.

function Grab-PDFs {
    [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $browse = New-Object System.Windows.Forms.FolderBrowserDialog
    $browse.SelectedPath = "C:\"
    $browse.ShowNewFolderButton = $false
    $browse.Description = "Select a directory"

    $loop = $true
    while($loop)
    {
        if ($browse.ShowDialog() -eq "OK")
        {
        $loop = $false
		
		cd $browse.SelectedPath
		
		# Grab PDFs from web page
		
		$psPage = Invoke-WebRequest "http://www.example.com/path/to/pdfs"
		$urls = $psPage.ParsedHtml.getElementsByTagName("A") | ? {$_.href -like "*.pdf"} | Select-Object -ExpandProperty href

		$urls | ForEach-Object {Invoke-WebRequest -Uri $_ -OutFile ($_ | Split-Path -Leaf)}
		
		Write-Host "... PDF downloading is complete." 
		[System.Windows.Forms.MessageBox]::Show("Your PDFs have been downloaded.", "Job Complete")
		
        } else
        {
            $res = [System.Windows.Forms.MessageBox]::Show("You clicked Cancel. Would you like to try again or exit?", "Select a location", [System.Windows.Forms.MessageBoxButtons]::RetryCancel)
            if($res -eq "Cancel")
            {
                #Ends script
                return
            }
        }
    }
    $browse.SelectedPath
    $browse.Dispose()
} Grab-PDFs

This code has also been uploaded to Github Gist.

   

Comments:

No comments have yet been submitted. Be the first!

Have your say:

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.