How can I pass default credentials to a PowerShell Web Client Object? Alternative to Invoke-WebRequest for PS v2?

EGr picture EGr · Sep 18, 2013 · Viewed 27.9k times · Source

I'm running the following code

$client = new-object System.Net.WebClient
$client.DownloadFile( $UriValue, "C:\Temp\BHRout.json" )
$json = Get-Content "C:\Temp\BHRout.json"

This does not work because it needs my prompts credentials passed into the download string function. I've used the above code to replace this:

$NagiosResults = Invoke-WebRequest -Uri $Uri -UseDefaultCredentials | ConvertFrom-Json

The only problem with this is that the server I'm running the script on doesn't have Powershell v3; so this will not work either. Is there an alternative to Invoke-WebRequest for Powershell v2? If not, is there a way to 'use default credentials' with a System.Net.WebClient object?

Answer

Goyuix picture Goyuix · Sep 18, 2013

Just set the UseDefaultCredentials property of the WebClient to $true and that will use the credentials of the current user for authentication.

$uri = "http://myserver/service"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$json = $wc.DownloadString($uri)