本文介绍了神秘主义:Invoke-WebRequest 只能通过 ISE 工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我今天玩了 3 个小时,不明白为什么?
I have killed 3 hours today and don't understand why?
我有简单的脚本:
$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 我看到下面的错误.
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
证明已附.
推荐答案
我在使用 RabbitMQ 时也遇到了同样的问题,原因是 URL 中 %2f
的转义.请参阅百分比编码斜杠(/")在请求派送
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
利用上述答案的技巧,它在 ISE 和控制台中都有效:
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"
这篇关于神秘主义:Invoke-WebRequest 只能通过 ISE 工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!