Accessing a Web site with PowerShell

This is just another quick sample of what you can do in PowerShell by leveraging the .Net framework.

Need to access a website? No problem. System.Net.WebRequest to the rescue!

Note that you can specify credentials, read all the data, follow the links, etc. Just depends on how far you want to go…

function start-http([string]$url)
{
	$routine  = "start-http:"

	trap
	{
		log $routine "Trap: access URL $url."
		log $routine "Error = $_"
		log $routine $_.InvocationInfo.PositionMessage
		continue
	}

	$request  = [System.Net.WebRequest]::Create($url);
	$request.UseDefaultCredentials = $true

	$response = $request.GetResponse()
	if ($response)
	{
		log $routine "response statuscode = " $response.StatusDescription
		log $routine "response characterset = " $response.CharacterSet
		log $routine "response length in bytes = " `
			$response.ContentLength.ToString()

		$response.Close()
	}
}

Until next time…

As always, if there are items you would like me to talk about, please drop me a line and let me know!


Follow me on twitter: @EssentialExch

Leave a Reply

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