Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I had a Powershell script that used Invoke-RestMethod that was working in powershell 3.0. However, I upgraded to powershell 4.0 to fix a bug in powershell 3. When I did so, my script seems to have stopped working.

$username = "Administrator" $password = "PASSWORD" $uri = "https://10.0.0.18/vmrest/users" $dictionary = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f$username,$password))) $dictionary.Add("Authorization",$base64AuthInfo) Invoke-RestMethod -Uri $uri -Method GET -Headers $dictionary -Verbose

When I turn on the verbose switch, it gives me this response

VERBOSE: GET https://192.168.1.18/vmrest/users with 0-byte payload VERBOSE: received -1-byte response of content type

I also tried specifying the requested content type, but no dice $dictionary.Add("Accept","application/json") $dictionary.Add("Connection", "keep_alive")

share|improve this question

2 Answers 2

up vote 8 down vote accepted

One thing that sticks out at me is that since you're using HTTPS, I'm sure you must be getting certificate errors since your URL is an IP address.

You need to tell Powershell (the .NET framework, really,) to ignore certificate errors. Or else it will crap out on things such as Invoke-WebRequest.

Try this:

[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

It's a custom certificate validation callback that always returns true thereby effectively ignoring certificate problems.

share|improve this answer
    
Good call. I had code in my poweshell 3.0 script that did that, but somehow I must have deleted it before I started testing in PS4. However, now I have this error: "Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send." –  Brett G Aug 12 at 14:17
    
Check out the resolutions A,D,E,F and O on this page: support.microsoft.com/kb/915599 since you are adding your own headers, you're overriding some of the built-in .NET functionality here. Keepalive, 100-Continue, etc. –  Ryan Ries Aug 12 at 14:34

Probably not an answer to your problem, but another point is that you don't have to construct basic authentication headers yourself:

$secPw = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object PSCredential -ArgumentList $username,$secPw

Invoke-RestMethod -Uri $uri -Method Get -Credential $cred

It's especially useful if you're interactively prompting for credentials because you can just use Get-Credential and be done with it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.