【问题标题】:Mysticism: Invoke-WebRequest working only via ISE神秘主义:仅通过 ISE 工作的 Invoke-WebRequest
【发布时间】:2017-06-15 17:33:44
【问题描述】:

我今天已经杀了 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

【问题讨论】:

    标签: powershell powershell-4.0


    【解决方案1】:

    我在使用 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"
    

    【讨论】:

      猜你喜欢
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2021-10-17
      • 2018-05-15
      • 1970-01-01
      相关资源
      最近更新 更多