Powershell – How to use PowerShell invoke-webrequest with Windows Authentication and Username\Password

powershellrestweb services

The following PowerShell invoke-webrequest works for me when the Windows Service I'm running it from has permission to call the webservice. However, this isn't always the case.

I need to the ability to use Windows Authentication but also set the account username\password for the call. Does anyone have some sample code for doing this?

Invoke-WebRequest -UseBasicParsing "url" -UseDefaultCredentials -Method GET

Best Answer

You may set the UseDefaultCredentials property of Invoke-WebRequest module to true. Link to the official doc: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-6

$url = "http://yourURL"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$response = $wc.DownloadString($url)