Search code examples
htmlpowershellauthenticationweb-scrapingprompt

How to post credentials to prompt window with Invoke-WebRequest


I am trying to build a PowerShell script which logs in to a site and downloads a file. However the site does not have the username / password fields in a form, like most sites. When navigating to the site, it immediately opens a prompt looking like:

Authentication Required Prompt

My question is how would I send an Invoke-WebRequest to post a username and password and login to the site. Traditionally, I have been finding the username and password by their ID attribute and setting their values but this is not possible with this prompt. Any ideas? Thanks


Solution

  • Invoke-WebRequest takes a -Credential object.

    You can do something like:

    $cred = Get-Credential
    Invoke-WebRequest -Uri 'https://mysite' -Credential $cred
    

    or if you wanted your password (INSECURELY) in a variable you can:

    $user = "user"
    $pass = "password"
    $securepasswd = ConvertTo-SecureString $pass -AsPlainText -Force
    $cred = New-Object System.Management.Automation.PSCredential($user, $securepasswd)
    
    Invoke-WebRequest -Uri 'https://mysite' -Credential $cred