Using PowerShell for login scripts (HTTP POST)

Here’s a small example of how to use PowerShell to pretend it’s a web browser to login to a service. In my case it’s used to let my computer get access to a customer’s network, but it could also be used to login to other services, such as public WiFi services, etc. It also serves as an example of how to do a HTTP POST operation in PowerShell, something that can be very useful in many situations.

param($username=($env:username), $password=$(throw "The 'password' parameter is required!"))

$nvc = new-object System.Collections.Specialized.NameValueCollection
$wc = new-object net.webclient
[void] $wc.UploadValues('', $nvc)

The code is very simple:

  • The script takes two parameters, $username and $password. Note the use of default values to get the logged in user’s username into $username (if it’s not given by the caller) and mark $password as required (an exception is thrown if the parameter is not given). The last in particular is not very obvious if you ask me.
  • We then initialize a normal .Net NameValueCollection with the names and values of the fields to post (i.e. names of the input elements in the HTTP form we’re imitating)
  • The actual HTTP-posting is done using the UploadValues method of System.Net.WebClient object.

I think simple examples like this really shows the potential of PowerShell and that making .Net types so easily accessible in the language was a really smart design desicion by the language designers.


2 thoughts on “Using PowerShell for login scripts (HTTP POST)”

  1. Yes, I don’t see why not. You would have to read the HTML code on the login form carefully and update the above script of course, but other than that it shouldn’t be a problem. Unless they use some form of manual validation (e.g. typing letters from a generated image)…

    Whether the bulletin board remembers the authorization so that you can open in a web browser without logging in is another question (in my example the service in question does remember). In any case, you should be okay if you only use the web client instance from the script.


Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.