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.
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"
Related
I am getting an error while using this code
$hookUrl = 'https://discord.com/api/webhooks/977171177120358412/U8T5Nv5BDCOL70IeXyPjA8Vlxo-4BB2b6QXhG0nAwD_gsw2AHXCSbbcjmiFvLlFFZD6I'
$content = #"
You can enter your message content here.
With a here-string, new lines are included as well!
Enjoy.
"#
$payload = [PSCustomObject]#{
content = $content
}
Invoke-RestMethod -Uri $hookUrl -Method Post -Body ($payload | ConvertTo-Json)
Invoke-RestMethod : {"message": "Cannot send an empty message", "code": 50006}
At line:17 char:1
+ Invoke-RestMethod -Uri $hookUrl -Method Post -Body ($payload | Conver ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have no idea where I made a mistake, I would be glad if you could help me.
Invoke-restmethod -Uri $hookUrl -Method Post -Body ($payload | ConvertTo-Json) -Headers #{ "Content-Type" = "application/json" }
This seems to work
I have been working with Powershell all day, playing with proxy settings and related. A POST request that once worked earlier in the day, is now stating a very bizarre error:
The request:
$tenantId = '8331e1..........'
$client_id = 'a3b869ef................
$client_secret = '0w;m$................'
#************ GET AAD TOKEN ************
$url = "https://login.microsoftonline.com/" + $tenantId + "/oauth2/token"
$body = #{
grant_type = 'client_credentials'
client_id = $client_id
client_secret = $client_secret
resource = 'https://dev.azuresynapse.net'
}
$GetAADResult = Invoke-WebRequest -Method 'Post' -Uri $url -Body $body
$GetAAD_Content_JSON = $GetAADResult.Content | ConvertFrom-Json
$access_token = $GetAAD_Content_JSON.access_token
# print access_token
$access_token
This used to provide a simple token as a response, but now it is returning the error:
Invoke-WebRequest : The remote name could not be resolved: 'http'
At line:24 char:17
+ ... GetAADResult = Invoke-WebRequest -Method 'Post' -Uri $url -Body $body
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : System.Net.WebException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
ConvertFrom-Json : Cannot bind argument to parameter 'InputObject' because it is null.
At line:26 char:48
+ $GetAAD_Content_JSON = $GetAADResult.Content | ConvertFrom-Json
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [ConvertFrom-Json], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertFromJsonCommand
I do not know what needs to change to get this functionating again, it appears PowerShell is looking for a proxy setting in every request...? Anny ideas?
I ended up undoing these steps: https://spaghettidba.com/2017/12/19/recovering-the-psgallery-repository-behind-a-corporate-proxy/
I would like to use an POST request with powershell but am getting the following errormessage. I have searched many hours, but can't find the problem. The json body seems also to be correct(?).
Thanks in advance for every help!
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
(New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$body = #{
"client"="myKey"
"request-type"="authentication"
"username"="myUsr"
"password"="myPwd"
} | ConvertTo-Json -Depth 10
$header = #{
"Content-Type"="application/x-www-form-urlencoded"
}
$res = Invoke-RestMethod -Uri "https://myUrl:4000/abc" -Method 'POST' -Body $body -Headers $header
Invoke-RestMethod :
Error
Cannot POST /abc
In Zeile:1 Zeichen:8
+ $res = Invoke-RestMethod -Uri "https://myUrl:400 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Edit:
I have edited my code but get the same error:
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
(New-Object System.Net.WebClient).Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$body = #{
"client"="mykey"
"request-type"="authentication"
"username"="myusr"
"password"="mypw"
}
$res = Invoke-RestMethod -Uri "https://myUrl:4000/abc" -Method 'POST' -Body $body
And the 400 error is'nt a error code, I think it's the port.
Invoke-RestMethod :
Error
Cannot POST /abc
In Zeile:1 Zeichen:8
+ $res = Invoke-RestMethod -Uri "https://myUrl:400 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
The request should look like the following:
client=sadsda42424242&request-type=authentication&username=extern&password=geheim
Also I have to use the content type „application/x-www-form-urlencoded“.
for some reason I got stuck with an simple Invoke-WebRequest. I need to send an XML-File to a website by Method "POST" and enc-Type "multipart/form-data". My code:
$SupraliftXML="C:\supralift.xml"
$Uri = 'https://www.supralift.com/servlet/EcutServlet?handler=BulkloadHandler&jfaction=0'
$Form = #{
muddledPassword = 'mypassword'
userID = 'myuserID'
XMLfile = Get-Item -Path $SupraliftXML
}
$Result = Invoke-RestMethod -AllowUnencryptedAuthentication -Uri $Uri -Method Post -Form $Form
I got an error that there is no parameter like "-form"
$Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Thank you for any help!
I am trying to post data to a URL using PowerShells Invoke-RestMethod however I constantly keep getting this message:
+ $response.RawContent
+ ~
Unexpected token '' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Am I missing an escape of a string literal somewhere or malformed quote mark?
$user = "username"
$pass = "password"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')
$headers.Add('Content-Type','application/json')
$uri = "http://myurl.com"
$params = #{
message = "hello world"
}
$response = Invoke-RestMethod -Method Post -Headers $headers -Uri $uri -Body $params
$response.RawContent
Removed $response.RawContent and it works. Changed it to echo $response to see output.