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 $nvc.Add('username',$username) $nvc.Add('password',$password) $wc = new-object net.webclient [void] $wc.UploadValues('http://123.123.123.123/loginuser', $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.
/Emil
Nice,
is there a way to log into a baord e.g. vBulletin?
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.
/Emil