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://126.96.36.199/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.