Hi all - I have a bunch of servers that need to use the REST API to get/post/delete stuff from an internal webserver (each server needs to self-register/modify/remove itself as appropriate), so it has to be run locally).
This works fine using invoke-webrequest on the PS3 & newer boxes, but a number are running PS2, which won’t be upgraded (we are slowly migrating these over to newer VMs). When using System.Net.WebRequest and the same credentials, I consistently get ‘403 Forbidden’ errors. Am I correct in thinking that the credentials aren’t even being passed? I’ve been researching this for ages and trying various settings, but it’s hard to find much besides “hey, you should use invoke-webrequest instead.” So at this point I’ve far exceeded my shallow understanding of REST and am pretty much just a monkey on a typewriter. Any help would be appreciated.
PS C:\> # Credentials $User = "foo" $PW = "bar" $SecPW = ConvertTo-SecureString $PW -AsPlainText -Force $Cred = New-Object System.Management.Automation.PSCredential ($User, $SecPW) PS C:\> # This works! All is well. Invoke-WebRequest -Uri $URI -Credential $Cred -Method Get -Headers @{ACCEPT="application/json"} | Select StatusCode,StatusDescription,BaseResponse StatusCode StatusDescription BaseResponse ---------- ----------------- ------------ 200 OK System.Net.HttpWebResponse PS C:\> # This doesn't work. $Request = [System.Net.WebRequest]::Create($URI) $Request.ContentType = "application/json" $Request.Credentials = $Cred $Request.Method = "GET" $Request.GetResponse() Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (403) Forbidden." At line:6 char:1 + $Request.GetResponse() + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException PS C:\> # Nor does this... $Request = [System.Net.WebRequest]::Create($URI) $Request.Headers.Add("AUTHORIZATION", "Basic, $Cred") $Request.PreAuthenticate = $true $Request.Credentials = $Cred $Request.Method = "GET" $request.ContentType = "application/json" $Request.GetResponse() Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (403) Forbidden." At line:8 char:1 + $Request.GetResponse() + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : WebException