default
default

Reputation: 41

Mysticism: Invoke-WebRequest working only via ISE

I have killed 3 hours today and don't understand why?

I have easy script:

$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

So, via PS ISE it works perfectly, but via powershell.exe I see an error below.

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

Proof attached.

Upvotes: 3

Views: 1553

Answers (1)

PlageMan
PlageMan

Reputation: 792

I had also the same problem with RabbitMQ, the cause is the escaping of %2f in URL. See Percent-encoded slash (“/”) is decoded before the request dispatch

With the tricks of the above answer, it works both in ISE and console :

$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"

Upvotes: 0

Related Questions