Invoke-Restmethod在PS 4.0中打破了脚本

我有一个Powershell脚本,使用PowerShell 3.0中的Invoke-RestMethod。 但是,我升级到PowerShell 4.0来修复PowerShell 3中的错误。当我这样做,我的脚本似乎已经停止工作。

$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

当我打开详细的开关,它给了我这个回应

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

我也尝试指定请求的内容types,但没有骰子$dictionary.Add("Accept","application/json") $dictionary.Add("Connection", "keep_alive")

有一件事情就是因为你使用的是HTTPS,所以我相信你必须得到证书错误,因为你的URL是一个IP地址。

您需要告诉Powershell(.NET框架),以忽略证书错误。 否则,它会暴露在诸如Invoke-WebRequest之类的东西上。

尝试这个:

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

这是一个自定义的证书validationcallback,始终返回true,从而有效地忽略证书问题。

可能不是您的问题的答案,但另一点是您不必自己构build基本的身份validation标头:

 $secPw = ConvertTo-SecureString $password -AsPlainText -Force $cred = New-Object PSCredential -ArgumentList $username,$secPw Invoke-RestMethod -Uri $uri -Method Get -Credential $cred 

如果您交互式地提示input凭据,那么它就特别有用,因为您可以使用Get-Credential并使用它。