Introduction
Recently, one of my clients had a need to automatically download a file from a public-facing state government website. Normally, this can easily be done in a number of ways. Powershell is the first way that comes to mind but you could also utilize scripting tools, such as wget or curl just to name a couple. However, thanks to the awesome power (note: sarcasm) of .NET Nuke, the download link is hidden behind JavaScript postback functionality.

Essentially, a postback is where a web page contains a form that consumes the data. This consumable data can be text fields or even a button/link click. When the form is submitted, the data from the form is then sent back to the same page that the form originated from. This is the “postback” of the process. The form “posts” data back to itself and returns the appropriate results. In this case, the result is a downloadable file.
Disclaimer: I’m not a Powershell expert by any means. Also, the script requires PowerShell 3.0 or higher due to some of the cmdlets used.
Script
In a nutshell, the script has to perform in the following manner.
- Obtain the URL from a variable.
- Get some session information so that we can “fake” out the server.
- Add a user site and a form.
- Create fields on the form and set them to the appropriate values.
- Specify a file name.
- Send the form back to the server.
So, let’s break this apart and walk through it.
Of course, this could be turned into a script that accepts variables directly. In this case, however, I don’t need to do this. The variable is statically set.
- #URL that needs to be fetched
- $url = "https://site.state.gov/default.aspx"
- #get the server name in case the process jumps to another script
- $serverName = $env:computername
While I am here, I also retrieve the server name. This is done so that if the script is going to be moved to another server, the process itself shouldn’t break. I tried to use a little forward thinking here.
Next, I’ll use the Invoke-WebRequest with the $url variable along with the -SessionVariable switch. This switch will create a web request session object and assign it to the specified variable, called “session”. Also, note that I am putting things into a TRY/CATCH block as I want to make sure something happens if things go south during this process.
- TRY {
- #use invoke-webrequest to fetch a session from the site
- Invoke-WebRequest $url -SessionVariable session -UseBasicParsing
Now, we’ll call the Invoke-WebRequest cmdlet again against the same URL that was used originally. This will allow us to obtain the form from the page, which contains.
- #add a site using the session information from the above web request
- $addUserSite = Invoke-WebRequest $url -WebSession $session #get the website $url using the session contained in $session
- $addUserForm = $addUserSite.Forms[0] #Invoke-WebRequest does a lot of auto processing.

Sourabh SomaniPosted Mar 30, 2018, 1:22 AM
Awesome learn something new and interesting. :)