Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 270
EGr Avatar asked Sep 18 '13 21:09

EGr


People also ask

What is PowerShell invoke-WebRequest?

The Invoke-WebRequest cmdlet sends HTTP, HTTPS, FTP, and FILE requests to a web page or web service. It parses the response and returns collections of forms, links, images, and other significant HTML elements. This cmdlet was introduced in Windows PowerShell 3.0.

What is invoke REST method PowerShell?

Description. The Invoke-RestMethod cmdlet sends HTTP and HTTPS requests to Representational State Transfer (REST) web services that return richly structured data. PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returns the Item or Entry XML nodes.

How do I use REST API in PowerShell?

To call a REST API from the Windows PowerShell, you should use the Invoke-RestMethod cmdlet. A call to an API is simply a request through HTTP or HTTPS. So, you will need a URL to which the API will be sent. You can find detailed information about the URL to call to get data from API documentation.


1 Answers

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)
like image 142
Goyuix Avatar answered Oct 06 '22 16:10

Goyuix