PowerShell WebClient Example

UPDATE [August 2014] : I made an update to this post here.

 

I’m still amazed that PowerShell has no commandlet equivalent of WGET or CURL. Even in SQL Server Integration Services (SSIS) this is missing.

In the age of RESTful webservices, the official guidance (at the time of writing) is to write your own with custom .Net code. Seriously?!?

It seems they are indeed serious…

So here for your amusement is a simple  function you can use in your PS1 scripts. It calls the .Net WebClient class.

## Declare a function that takes source and destination arguments
Function Get-Webclient ($url, $out) {

$proxy = [System.Net.WebRequest]::GetSystemWebProxy()

$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials

$request = New-Object System.Net.WebCLient

$request.UseDefaultCredentials = $true ## Proxy credentials only

$request.Proxy.Credentials = $request.Credentials

$request.DownloadFile($url, $out)

}

## Call the function with our source and destination.
Get-Webclient "http://www.google.com" "C:\tmp\Foo3.txt"

But what if the destination is password protected and you need authentication credentials?

## Declare a function that takes source and destination arguments
Function Get-Webclient ($url, $out) {

$proxy = [System.Net.WebRequest]::GetSystemWebProxy()

$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials

$request = New-Object System.Net.WebCLient

$request.UseDefaultCredentials = $true

$request.Proxy.Credentials = $request.Credentials

$passwd	= ConvertTo-SecureString "mypassword" -AsPlainText -Force; ## Website credentials

$request.Credentials = New-Object System.Management.Automation.PSCredential ("username", $passwd);

$request.DownloadFile($url, $out)

}

## Call the function with our source and destination.
Get-Webclient "http://www.securedwebsite.com" "C:\tmp\Foo3.txt"