神秘主义:Invoke-WebRequest仅通过ISE工作

时间:2017-01-30 14:11:03

标签: powershell powershell-v4.0

我今天已经杀了3个小时而且不明白为什么?

我有简单的脚本:

$user = 'icm'
$pass = 'icm'
$pair = "$($user):$($pass)"
$url = 'http://####:15672/api/queues/%2f/ICM.Payments.Host.1'
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$headers = @{
    Authorization = $basicAuthValue
}
$request = Invoke-WebRequest -Uri $url -Headers $headers -ContentType "application/json"
$messages = ($request.Content | ConvertFrom-Json | Select -ExpandProperty messages)
$messages

所以,通过PS ISE它可以很好地工作,但是通过powershell.exe我看到下面的错误。

Invoke-WebRequest : {"error":"Object Not Found","reason":"\"Not Found\"\n"}
At C:\Temp\Untitled1.ps1:16 char:12
+ $request = Invoke-WebRequest -Uri $url -Headers $headers -ContentType ...
+            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At C:\Temp\Untitled1.ps1:17 char:33
+ $messages = ($request.Content | ConvertFrom-Json | Select -ExpandProp ...
+                                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand

证明attached

1 个答案:

答案 0 :(得分:0)

我对RabbitMQ也有同样的问题,原因是URL中%2f的转义。 见Percent-encoded slash (“/”) is decoded before the request dispatch

通过上述答案的技巧,它可以在ISE和控制台中运行:

$urlFixSrc = @" 
using System;
using System.Reflection;

public static class URLFix 
{ 
    public static void ForceCanonicalPathAndQuery(Uri uri)
    {
        string paq = uri.PathAndQuery;
        FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
        ulong flags = (ulong) flagsFieldInfo.GetValue(uri);
        flags &= ~((ulong) 0x30);
        flagsFieldInfo.SetValue(uri, flags);
    }
} 
"@ 
Add-Type -TypeDefinition $urlFixSrc -Language CSharp

$url = [URI]$url

Invoke-WebRequest -Uri $url -Headers $headers -ContentType "application/json"