Categories
geek microsoft programming

using a web client in powershell

Note, for Powershell v3.0 and v4.0 the Invoke-WebRequest (with curl & wget aliasses) is a better choice now.

PowerShell truly is powerful.
A few lines of script is all you need to perform an HTTP request in a PowerShell script. If the native commands don’t cut it, it’s pretty easy to reach out and harness the power of the .NET framework instead like in the sample below.
As a .NET developer this allows you to write some pretty kick-ass scripts without having to compile a line of code.

I like it.

# Add the necessary .NET assembly
Add-Type -AssemblyName System.Net.Http

# Create the HttpClient object
$client = New-Object -TypeName System.Net.Http.Httpclient

# Get the web content.
$task = $client.GetStringAsync("http://n3wjack.net")

# Wait for the async call to finish
$task.wait();

# Use the result
if ($task.IsCompleted) {
  # Do your thing here.
  echo $task.Result
} else {
  echo "Sorry, something went wrong: " + $task.Exception.Message
}

Leave a Reply

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

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