Login and download a file in web using powershell

Copper Contributor

I am quite new to PowerShell, what I am trying to do is to create script automation where I can log in to my account and click the download button from a website using Invoke-Web-Request. But whenever I open the downloaded file(CSV). It will just contain the HTML script from the login page.

Here are the codes I used:

$web = Invoke-WebRequest -uri "https://privatewebsite.com/" -SessionVariable sess    
$form = $web.forms[0]
$form.fields["id_username"] = "user123"
$form.Fields["id_password"] = "pass123"

$in = Invoke-WebRequest -uri ("https://privatewebsite.com/"+$form.Action) -WebSession $sess -Method POST -Body $form.Fields

Invoke-WebRequest -Uri "https://privatewebsite.com/users/report" -OutFile "C:\path\users.csv"


Login form from https://privatewebsite.com/:

<div class="login-panel__username">
          <label for="id_username">Username:</label>
          <input id="id_username" name="username" placeholder="Enter your username " type="text" />

        <div class="login-panel__password">
          <label for="id_password">Password:</label>
          <input id="id_password" name="password" placeholder="Enter your password" type="password" />

        <div class="login-panel__submit-wrapper">
             class="btn btn-primary btn-lg btn-block"

Code from https://privatewebsite.com/users/ containing the download button that will redirect to https://privatewebsite.com/users/report to download the file


<ul class="account__actions button-group right">
      <a href="https://privatewebsite.com/users/report"
         class="btn btn-lg btn-primary hz-hint hz-hint--bottom"
         data-hint="Download user report"
        <i class="fa fa-cloud-download-alt"></i>
            btn btn-lg btn-primary
            hz-hint hz-hint--bottom
          data-hint="Create user"
        <i class="fa fa-plus"></i>


Thanks in advance.









0 Replies