Powershell Invoke - RestMethod - powershell

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“.

Related

Webhook With PowerShell Discord

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

Invoke-WebRequest : The remote name could not be resolved: 'http'

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/

Using power shell to right a put method for SSRS API deployment for setting shareddataset

I want to use PowerShell to set shareddataset for a report using SSRS API.
I have already tried to use PowerShell to get shareddataset using SSRS API successfully. But failed to use put method.
Success using get method:
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/DataSets"
`
`$Body = #{
Path ="/Shared_data_sets/P_Calculate_date_Default_key";
output_mode = "csv";
earliest_time = "-2d#d";
latest_time = "-1d#d";
}
Invoke-RestMethod -Method 'GET' -Uri $url -Credential $Cred -Body $body -OutFile output.csv
failed using put method:
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6";
Name = "P_Calculate_Date_Default_Key";
Path = "/Shared_data_sets/P_Calculate_date_Default_key";
Type = "DataSet" ;
}
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method 'PUT'
Error returned is
The remote server returned an error: (400) Bad Request
detailed error:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request. At line:12 char:1 + Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method 'PU ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I hope the put method could be working. I thought I was using the same way as the get method but it still failed.
I tried another way but still failed :
$Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6"
Name = "P_Calculate_Date_Default_Key"
Path = "/Shared_data_sets/P_Calculate_date_Default_key"
Type = "DataSet"
}| ConvertTo-Json
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT -ContentType "application/json" | Out-Null
Just for you to know that for the put method, i have already tested on postman and it works. So I guess currently it is only due to some logic in powershell side inconsistent.
in postman I put the link as :
http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets
Body as :
[
{
"Id": "935be257-5a65-4c0d-b372-d5a6a188daf6",
"Name": "P_Calculate_Date_Default_Key",
"Path": "/Shared_data_sets/P_Calculate_date_Default_key",
"Type": "DataSet"
}
]
I tried your recommendation and it shows below , I have added it below all:
PS C:\Users\dkx42a8adm> $Cred = Get-Credential
$Url = "http://localhost/Reports/api/v2.0/Reports(23a6af79-9de3-49cb-b66b-625d3ff3909b)/SharedDataSets"
$Body = #{
Id = "935be257-5a65-4c0d-b372-d5a6a188daf6"
Name = "P_Calculate_Date_Default_Key"
Path = "/Shared_data_sets/P_Calculate_date_Default_key"
Type = "DataSet"
}| ConvertTo-Json
Write-Output $Body
Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT -ContentType "application/json"
$error[0]|format-list -force
cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
{
"Path": "/Shared_data_sets/P_Calculate_date_Default_key",
"Name": "P_Calculate_Date_Default_Key",
"Id": "935be257-5a65-4c0d-b372-d5a6a188daf6",
"Type": "DataSet"
}
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:14 char:1
+ Invoke-RestMethod -Uri $Url -Credential $Cred -Body $body -Method PUT ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Exception : System.Net.WebException: The remote server returned an error: (400) Bad Request.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
TargetObject : System.Net.HttpWebRequest
CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at , : line 14
PipelineIterationInfo : {}
PSMessageDetails :

Invoke-WebRequest error: no parameter like "-form"

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!

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